QueryTest.php 127 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 3.0.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\ORM;
  17. use Cake\Cache\Engine\FileEngine;
  18. use Cake\Database\Driver\Mysql;
  19. use Cake\Database\Driver\Sqlite;
  20. use Cake\Database\DriverFeatureEnum;
  21. use Cake\Database\Exception\DatabaseException;
  22. use Cake\Database\Expression\CommonTableExpression;
  23. use Cake\Database\Expression\FunctionExpression;
  24. use Cake\Database\Expression\IdentifierExpression;
  25. use Cake\Database\Expression\OrderByExpression;
  26. use Cake\Database\Expression\QueryExpression;
  27. use Cake\Database\StatementInterface;
  28. use Cake\Database\TypeMap;
  29. use Cake\Database\ValueBinder;
  30. use Cake\Datasource\ConnectionManager;
  31. use Cake\Datasource\ResultSetDecorator;
  32. use Cake\Event\EventInterface;
  33. use Cake\I18n\DateTime;
  34. use Cake\ORM\Association\BelongsTo;
  35. use Cake\ORM\Query;
  36. use Cake\ORM\ResultSet;
  37. use Cake\TestSuite\TestCase;
  38. use InvalidArgumentException;
  39. use ReflectionProperty;
  40. /**
  41. * Tests Query class
  42. */
  43. class QueryTest extends TestCase
  44. {
  45. /**
  46. * Fixture to be used
  47. *
  48. * @var array<string>
  49. */
  50. protected array $fixtures = [
  51. 'core.Articles',
  52. 'core.Tags',
  53. 'core.ArticlesTags',
  54. 'core.ArticlesTranslations',
  55. 'core.Authors',
  56. 'core.Comments',
  57. 'core.Datatypes',
  58. 'core.Posts',
  59. ];
  60. /**
  61. * @var \Cake\Database\Connection
  62. */
  63. protected $connection;
  64. /**
  65. * @var \Cake\ORM\Table
  66. */
  67. protected $table;
  68. /**
  69. * setUp method
  70. */
  71. public function setUp(): void
  72. {
  73. parent::setUp();
  74. $this->connection = ConnectionManager::get('test');
  75. $schema = [
  76. 'id' => ['type' => 'integer'],
  77. '_constraints' => [
  78. 'primary' => ['type' => 'primary', 'columns' => ['id']],
  79. ],
  80. ];
  81. $schema1 = [
  82. 'id' => ['type' => 'integer'],
  83. 'name' => ['type' => 'string'],
  84. 'phone' => ['type' => 'string'],
  85. '_constraints' => [
  86. 'primary' => ['type' => 'primary', 'columns' => ['id']],
  87. ],
  88. ];
  89. $schema2 = [
  90. 'id' => ['type' => 'integer'],
  91. 'total' => ['type' => 'string'],
  92. 'placed' => ['type' => 'datetime'],
  93. '_constraints' => [
  94. 'primary' => ['type' => 'primary', 'columns' => ['id']],
  95. ],
  96. ];
  97. $this->table = $this->getTableLocator()->get('foo', ['schema' => $schema]);
  98. $clients = $this->getTableLocator()->get('clients', ['schema' => $schema1]);
  99. $orders = $this->getTableLocator()->get('orders', ['schema' => $schema2]);
  100. $companies = $this->getTableLocator()->get('companies', ['schema' => $schema, 'table' => 'organizations']);
  101. $orderTypes = $this->getTableLocator()->get('orderTypes', ['schema' => $schema]);
  102. $stuff = $this->getTableLocator()->get('stuff', ['schema' => $schema, 'table' => 'things']);
  103. $stuffTypes = $this->getTableLocator()->get('stuffTypes', ['schema' => $schema]);
  104. $categories = $this->getTableLocator()->get('categories', ['schema' => $schema]);
  105. $this->table->belongsTo('clients');
  106. $clients->hasOne('orders');
  107. $clients->belongsTo('companies');
  108. $orders->belongsTo('orderTypes');
  109. $orders->hasOne('stuff');
  110. $stuff->belongsTo('stuffTypes');
  111. $companies->belongsTo('categories');
  112. }
  113. /**
  114. * Data provider for the two types of strategies HasMany implements
  115. *
  116. * @return array
  117. */
  118. public function strategiesProviderHasMany(): array
  119. {
  120. return [['subquery'], ['select']];
  121. }
  122. /**
  123. * Data provider for the two types of strategies BelongsTo implements
  124. *
  125. * @return array
  126. */
  127. public function strategiesProviderBelongsTo(): array
  128. {
  129. return [['join'], ['select']];
  130. }
  131. /**
  132. * Data provider for the two types of strategies BelongsToMany implements
  133. *
  134. * @return array
  135. */
  136. public function strategiesProviderBelongsToMany(): array
  137. {
  138. return [['subquery'], ['select']];
  139. }
  140. /**
  141. * Test getRepository() method.
  142. */
  143. public function testGetRepository(): void
  144. {
  145. $query = new Query($this->connection, $this->table);
  146. $result = $query->getRepository();
  147. $this->assertSame($this->table, $result);
  148. }
  149. /**
  150. * Tests that results are grouped correctly when using contain()
  151. * and results are not hydrated
  152. *
  153. * @dataProvider strategiesProviderBelongsTo
  154. */
  155. public function testContainResultFetchingOneLevel(string $strategy): void
  156. {
  157. $table = $this->getTableLocator()->get('articles', ['table' => 'articles']);
  158. $table->belongsTo('authors', ['strategy' => $strategy]);
  159. $query = new Query($this->connection, $table);
  160. $results = $query->select()
  161. ->contain('authors')
  162. ->enableHydration(false)
  163. ->order(['articles.id' => 'asc'])
  164. ->toArray();
  165. $expected = [
  166. [
  167. 'id' => 1,
  168. 'title' => 'First Article',
  169. 'body' => 'First Article Body',
  170. 'author_id' => 1,
  171. 'published' => 'Y',
  172. 'author' => [
  173. 'id' => 1,
  174. 'name' => 'mariano',
  175. ],
  176. ],
  177. [
  178. 'id' => 2,
  179. 'title' => 'Second Article',
  180. 'body' => 'Second Article Body',
  181. 'author_id' => 3,
  182. 'published' => 'Y',
  183. 'author' => [
  184. 'id' => 3,
  185. 'name' => 'larry',
  186. ],
  187. ],
  188. [
  189. 'id' => 3,
  190. 'title' => 'Third Article',
  191. 'body' => 'Third Article Body',
  192. 'author_id' => 1,
  193. 'published' => 'Y',
  194. 'author' => [
  195. 'id' => 1,
  196. 'name' => 'mariano',
  197. ],
  198. ],
  199. ];
  200. $this->assertEquals($expected, $results);
  201. }
  202. /**
  203. * Tests that HasMany associations are correctly eager loaded and results
  204. * correctly nested when no hydration is used
  205. * Also that the query object passes the correct parent model keys to the
  206. * association objects in order to perform eager loading with select strategy
  207. *
  208. * @dataProvider strategiesProviderHasMany
  209. */
  210. public function testHasManyEagerLoadingNoHydration(string $strategy): void
  211. {
  212. $table = $this->getTableLocator()->get('authors');
  213. $this->getTableLocator()->get('articles');
  214. $table->hasMany('articles', [
  215. 'propertyName' => 'articles',
  216. 'strategy' => $strategy,
  217. 'sort' => ['articles.id' => 'asc'],
  218. ]);
  219. $query = new Query($this->connection, $table);
  220. $results = $query->select()
  221. ->contain('articles')
  222. ->enableHydration(false)
  223. ->toArray();
  224. $expected = [
  225. [
  226. 'id' => 1,
  227. 'name' => 'mariano',
  228. 'articles' => [
  229. [
  230. 'id' => 1,
  231. 'title' => 'First Article',
  232. 'body' => 'First Article Body',
  233. 'author_id' => 1,
  234. 'published' => 'Y',
  235. ],
  236. [
  237. 'id' => 3,
  238. 'title' => 'Third Article',
  239. 'body' => 'Third Article Body',
  240. 'author_id' => 1,
  241. 'published' => 'Y',
  242. ],
  243. ],
  244. ],
  245. [
  246. 'id' => 2,
  247. 'name' => 'nate',
  248. 'articles' => [],
  249. ],
  250. [
  251. 'id' => 3,
  252. 'name' => 'larry',
  253. 'articles' => [
  254. [
  255. 'id' => 2,
  256. 'title' => 'Second Article',
  257. 'body' => 'Second Article Body',
  258. 'author_id' => 3,
  259. 'published' => 'Y',
  260. ],
  261. ],
  262. ],
  263. [
  264. 'id' => 4,
  265. 'name' => 'garrett',
  266. 'articles' => [],
  267. ],
  268. ];
  269. $this->assertEquals($expected, $results);
  270. $results = $query->setRepository($table)
  271. ->select()
  272. ->contain(['articles' => ['conditions' => ['articles.id' => 2]]])
  273. ->enableHydration(false)
  274. ->toArray();
  275. $expected[0]['articles'] = [];
  276. $this->assertEquals($expected, $results);
  277. $this->assertEquals($table->getAssociation('articles')->getStrategy(), $strategy);
  278. }
  279. /**
  280. * Tests that it is possible to count results containing hasMany associations
  281. * both hydrating and not hydrating the results.
  282. *
  283. * @dataProvider strategiesProviderHasMany
  284. */
  285. public function testHasManyEagerLoadingCount(string $strategy): void
  286. {
  287. $table = $this->getTableLocator()->get('authors');
  288. $this->getTableLocator()->get('articles');
  289. $table->hasMany('articles', [
  290. 'property' => 'articles',
  291. 'strategy' => $strategy,
  292. 'sort' => ['articles.id' => 'asc'],
  293. ]);
  294. $query = new Query($this->connection, $table);
  295. $query = $query->select()
  296. ->contain('articles');
  297. $expected = 4;
  298. $results = $query->enableHydration(false)
  299. ->count();
  300. $this->assertEquals($expected, $results);
  301. $results = $query->enableHydration(true)
  302. ->count();
  303. $this->assertEquals($expected, $results);
  304. }
  305. /**
  306. * Tests that it is possible to set fields & order in a hasMany result set
  307. *
  308. * @dataProvider strategiesProviderHasMany
  309. */
  310. public function testHasManyEagerLoadingFieldsAndOrderNoHydration(string $strategy): void
  311. {
  312. $table = $this->getTableLocator()->get('authors');
  313. $this->getTableLocator()->get('articles');
  314. $table->hasMany('articles', ['propertyName' => 'articles'] + compact('strategy'));
  315. $query = new Query($this->connection, $table);
  316. $results = $query->select()
  317. ->contain([
  318. 'articles' => [
  319. 'fields' => ['title', 'author_id'],
  320. 'sort' => ['articles.id' => 'DESC'],
  321. ],
  322. ])
  323. ->enableHydration(false)
  324. ->toArray();
  325. $expected = [
  326. [
  327. 'id' => 1,
  328. 'name' => 'mariano',
  329. 'articles' => [
  330. ['title' => 'Third Article', 'author_id' => 1],
  331. ['title' => 'First Article', 'author_id' => 1],
  332. ],
  333. ],
  334. [
  335. 'id' => 2,
  336. 'name' => 'nate',
  337. 'articles' => [],
  338. ],
  339. [
  340. 'id' => 3,
  341. 'name' => 'larry',
  342. 'articles' => [
  343. ['title' => 'Second Article', 'author_id' => 3],
  344. ],
  345. ],
  346. [
  347. 'id' => 4,
  348. 'name' => 'garrett',
  349. 'articles' => [],
  350. ],
  351. ];
  352. $this->assertEquals($expected, $results);
  353. }
  354. /**
  355. * Tests that deep associations can be eagerly loaded
  356. *
  357. * @dataProvider strategiesProviderHasMany
  358. */
  359. public function testHasManyEagerLoadingDeep(string $strategy): void
  360. {
  361. $table = $this->getTableLocator()->get('authors');
  362. $article = $this->getTableLocator()->get('articles');
  363. $table->hasMany('articles', [
  364. 'propertyName' => 'articles',
  365. 'strategy' => $strategy,
  366. 'sort' => ['articles.id' => 'asc'],
  367. ]);
  368. $article->belongsTo('authors');
  369. $query = new Query($this->connection, $table);
  370. $results = $query->select()
  371. ->contain(['articles' => ['authors']])
  372. ->enableHydration(false)
  373. ->toArray();
  374. $expected = [
  375. [
  376. 'id' => 1,
  377. 'name' => 'mariano',
  378. 'articles' => [
  379. [
  380. 'id' => 1,
  381. 'title' => 'First Article',
  382. 'author_id' => 1,
  383. 'body' => 'First Article Body',
  384. 'published' => 'Y',
  385. 'author' => ['id' => 1, 'name' => 'mariano'],
  386. ],
  387. [
  388. 'id' => 3,
  389. 'title' => 'Third Article',
  390. 'author_id' => 1,
  391. 'body' => 'Third Article Body',
  392. 'published' => 'Y',
  393. 'author' => ['id' => 1, 'name' => 'mariano'],
  394. ],
  395. ],
  396. ],
  397. [
  398. 'id' => 2,
  399. 'name' => 'nate',
  400. 'articles' => [],
  401. ],
  402. [
  403. 'id' => 3,
  404. 'name' => 'larry',
  405. 'articles' => [
  406. [
  407. 'id' => 2,
  408. 'title' => 'Second Article',
  409. 'author_id' => 3,
  410. 'body' => 'Second Article Body',
  411. 'published' => 'Y',
  412. 'author' => ['id' => 3, 'name' => 'larry'],
  413. ],
  414. ],
  415. ],
  416. [
  417. 'id' => 4,
  418. 'name' => 'garrett',
  419. 'articles' => [],
  420. ],
  421. ];
  422. $this->assertEquals($expected, $results);
  423. }
  424. /**
  425. * Tests that hasMany associations can be loaded even when related to a secondary
  426. * model in the query
  427. *
  428. * @dataProvider strategiesProviderHasMany
  429. */
  430. public function testHasManyEagerLoadingFromSecondaryTable(string $strategy): void
  431. {
  432. $author = $this->getTableLocator()->get('authors');
  433. $article = $this->getTableLocator()->get('articles');
  434. $post = $this->getTableLocator()->get('posts');
  435. $author->hasMany('posts', [
  436. 'sort' => ['posts.id' => 'ASC'],
  437. 'strategy' => $strategy,
  438. ]);
  439. $article->belongsTo('authors');
  440. $query = new Query($this->connection, $article);
  441. $results = $query->select()
  442. ->contain(['authors' => ['posts']])
  443. ->order(['articles.id' => 'ASC'])
  444. ->enableHydration(false)
  445. ->toArray();
  446. $expected = [
  447. [
  448. 'id' => 1,
  449. 'title' => 'First Article',
  450. 'body' => 'First Article Body',
  451. 'author_id' => 1,
  452. 'published' => 'Y',
  453. 'author' => [
  454. 'id' => 1,
  455. 'name' => 'mariano',
  456. 'posts' => [
  457. [
  458. 'id' => '1',
  459. 'title' => 'First Post',
  460. 'body' => 'First Post Body',
  461. 'author_id' => 1,
  462. 'published' => 'Y',
  463. ],
  464. [
  465. 'id' => '3',
  466. 'title' => 'Third Post',
  467. 'body' => 'Third Post Body',
  468. 'author_id' => 1,
  469. 'published' => 'Y',
  470. ],
  471. ],
  472. ],
  473. ],
  474. [
  475. 'id' => 2,
  476. 'title' => 'Second Article',
  477. 'body' => 'Second Article Body',
  478. 'author_id' => 3,
  479. 'published' => 'Y',
  480. 'author' => [
  481. 'id' => 3,
  482. 'name' => 'larry',
  483. 'posts' => [
  484. [
  485. 'id' => 2,
  486. 'title' => 'Second Post',
  487. 'body' => 'Second Post Body',
  488. 'author_id' => 3,
  489. 'published' => 'Y',
  490. ],
  491. ],
  492. ],
  493. ],
  494. [
  495. 'id' => 3,
  496. 'title' => 'Third Article',
  497. 'body' => 'Third Article Body',
  498. 'author_id' => 1,
  499. 'published' => 'Y',
  500. 'author' => [
  501. 'id' => 1,
  502. 'name' => 'mariano',
  503. 'posts' => [
  504. [
  505. 'id' => '1',
  506. 'title' => 'First Post',
  507. 'body' => 'First Post Body',
  508. 'author_id' => 1,
  509. 'published' => 'Y',
  510. ],
  511. [
  512. 'id' => '3',
  513. 'title' => 'Third Post',
  514. 'body' => 'Third Post Body',
  515. 'author_id' => 1,
  516. 'published' => 'Y',
  517. ],
  518. ],
  519. ],
  520. ],
  521. ];
  522. $this->assertEquals($expected, $results);
  523. }
  524. /**
  525. * Tests that BelongsToMany associations are correctly eager loaded.
  526. * Also that the query object passes the correct parent model keys to the
  527. * association objects in order to perform eager loading with select strategy
  528. *
  529. * @dataProvider strategiesProviderBelongsToMany
  530. */
  531. public function testBelongsToManyEagerLoadingNoHydration(string $strategy): void
  532. {
  533. $table = $this->getTableLocator()->get('Articles');
  534. $this->getTableLocator()->get('Tags');
  535. $this->getTableLocator()->get('ArticlesTags', [
  536. 'table' => 'articles_tags',
  537. ]);
  538. $table->belongsToMany('Tags', [
  539. 'strategy' => $strategy,
  540. 'sort' => 'tag_id',
  541. ]);
  542. $query = new Query($this->connection, $table);
  543. $results = $query->select()->contain('Tags')->disableHydration()->toArray();
  544. $expected = [
  545. [
  546. 'id' => 1,
  547. 'author_id' => 1,
  548. 'title' => 'First Article',
  549. 'body' => 'First Article Body',
  550. 'published' => 'Y',
  551. 'tags' => [
  552. [
  553. 'id' => 1,
  554. 'name' => 'tag1',
  555. '_joinData' => ['article_id' => 1, 'tag_id' => 1],
  556. 'description' => 'A big description',
  557. 'created' => new DateTime('2016-01-01 00:00'),
  558. ],
  559. [
  560. 'id' => 2,
  561. 'name' => 'tag2',
  562. '_joinData' => ['article_id' => 1, 'tag_id' => 2],
  563. 'description' => 'Another big description',
  564. 'created' => new DateTime('2016-01-01 00:00'),
  565. ],
  566. ],
  567. ],
  568. [
  569. 'id' => 2,
  570. 'title' => 'Second Article',
  571. 'body' => 'Second Article Body',
  572. 'author_id' => 3,
  573. 'published' => 'Y',
  574. 'tags' => [
  575. [
  576. 'id' => 1,
  577. 'name' => 'tag1',
  578. '_joinData' => ['article_id' => 2, 'tag_id' => 1],
  579. 'description' => 'A big description',
  580. 'created' => new DateTime('2016-01-01 00:00'),
  581. ],
  582. [
  583. 'id' => 3,
  584. 'name' => 'tag3',
  585. '_joinData' => ['article_id' => 2, 'tag_id' => 3],
  586. 'description' => 'Yet another one',
  587. 'created' => new DateTime('2016-01-01 00:00'),
  588. ],
  589. ],
  590. ],
  591. [
  592. 'id' => 3,
  593. 'title' => 'Third Article',
  594. 'body' => 'Third Article Body',
  595. 'author_id' => 1,
  596. 'published' => 'Y',
  597. 'tags' => [],
  598. ],
  599. ];
  600. $this->assertEquals($expected, $results);
  601. $results = $query->select()
  602. ->contain(['Tags' => ['conditions' => ['Tags.id' => 3]]])
  603. ->disableHydration()
  604. ->toArray();
  605. $expected = [
  606. [
  607. 'id' => 1,
  608. 'author_id' => 1,
  609. 'title' => 'First Article',
  610. 'body' => 'First Article Body',
  611. 'published' => 'Y',
  612. 'tags' => [],
  613. ],
  614. [
  615. 'id' => 2,
  616. 'title' => 'Second Article',
  617. 'body' => 'Second Article Body',
  618. 'author_id' => 3,
  619. 'published' => 'Y',
  620. 'tags' => [
  621. [
  622. 'id' => 3,
  623. 'name' => 'tag3',
  624. '_joinData' => ['article_id' => 2, 'tag_id' => 3],
  625. 'description' => 'Yet another one',
  626. 'created' => new DateTime('2016-01-01 00:00'),
  627. ],
  628. ],
  629. ],
  630. [
  631. 'id' => 3,
  632. 'title' => 'Third Article',
  633. 'body' => 'Third Article Body',
  634. 'author_id' => 1,
  635. 'published' => 'Y',
  636. 'tags' => [],
  637. ],
  638. ];
  639. $this->assertEquals($expected, $results);
  640. $this->assertEquals($table->getAssociation('Tags')->getStrategy(), $strategy);
  641. }
  642. /**
  643. * Tests that tables results can be filtered by the result of a HasMany
  644. */
  645. public function testFilteringByHasManyNoHydration(): void
  646. {
  647. $query = new Query($this->connection, $this->table);
  648. $table = $this->getTableLocator()->get('Articles');
  649. $table->hasMany('Comments');
  650. $results = $query->setRepository($table)
  651. ->select()
  652. ->disableHydration()
  653. ->matching('Comments', function ($q) {
  654. return $q->where(['Comments.user_id' => 4]);
  655. })
  656. ->toArray();
  657. $expected = [
  658. [
  659. 'id' => 1,
  660. 'title' => 'First Article',
  661. 'body' => 'First Article Body',
  662. 'author_id' => 1,
  663. 'published' => 'Y',
  664. '_matchingData' => [
  665. 'Comments' => [
  666. 'id' => 2,
  667. 'article_id' => 1,
  668. 'user_id' => 4,
  669. 'comment' => 'Second Comment for First Article',
  670. 'published' => 'Y',
  671. 'created' => new DateTime('2007-03-18 10:47:23'),
  672. 'updated' => new DateTime('2007-03-18 10:49:31'),
  673. ],
  674. ],
  675. ],
  676. ];
  677. $this->assertEquals($expected, $results);
  678. }
  679. /**
  680. * Tests that tables results can be filtered by the result of a HasMany
  681. */
  682. public function testFilteringByHasManyHydration(): void
  683. {
  684. $table = $this->getTableLocator()->get('Articles');
  685. $query = new Query($this->connection, $table);
  686. $table->hasMany('Comments');
  687. $result = $query->setRepository($table)
  688. ->matching('Comments', function ($q) {
  689. return $q->where(['Comments.user_id' => 4]);
  690. })
  691. ->first();
  692. $this->assertInstanceOf('Cake\ORM\Entity', $result);
  693. $this->assertInstanceOf('Cake\ORM\Entity', $result->_matchingData['Comments']);
  694. $this->assertIsInt($result->_matchingData['Comments']->id);
  695. $this->assertInstanceOf(DateTime::class, $result->_matchingData['Comments']->created);
  696. }
  697. /**
  698. * Tests that BelongsToMany associations are correctly eager loaded.
  699. * Also that the query object passes the correct parent model keys to the
  700. * association objects in order to perform eager loading with select strategy
  701. */
  702. public function testFilteringByBelongsToManyNoHydration(): void
  703. {
  704. $query = new Query($this->connection, $this->table);
  705. $table = $this->getTableLocator()->get('Articles');
  706. $this->getTableLocator()->get('Tags');
  707. $this->getTableLocator()->get('ArticlesTags', [
  708. 'table' => 'articles_tags',
  709. ]);
  710. $table->belongsToMany('Tags');
  711. $results = $query->setRepository($table)->select()
  712. ->matching('Tags', function ($q) {
  713. return $q->where(['Tags.id' => 3]);
  714. })
  715. ->enableHydration(false)
  716. ->toArray();
  717. $expected = [
  718. [
  719. 'id' => 2,
  720. 'author_id' => 3,
  721. 'title' => 'Second Article',
  722. 'body' => 'Second Article Body',
  723. 'published' => 'Y',
  724. '_matchingData' => [
  725. 'Tags' => [
  726. 'id' => 3,
  727. 'name' => 'tag3',
  728. 'description' => 'Yet another one',
  729. 'created' => new DateTime('2016-01-01 00:00'),
  730. ],
  731. 'ArticlesTags' => ['article_id' => 2, 'tag_id' => 3],
  732. ],
  733. ],
  734. ];
  735. $this->assertEquals($expected, $results);
  736. $query = new Query($this->connection, $table);
  737. $results = $query->select()
  738. ->matching('Tags', function ($q) {
  739. return $q->where(['Tags.name' => 'tag2']);
  740. })
  741. ->enableHydration(false)
  742. ->toArray();
  743. $expected = [
  744. [
  745. 'id' => 1,
  746. 'title' => 'First Article',
  747. 'body' => 'First Article Body',
  748. 'author_id' => 1,
  749. 'published' => 'Y',
  750. '_matchingData' => [
  751. 'Tags' => [
  752. 'id' => 2,
  753. 'name' => 'tag2',
  754. 'description' => 'Another big description',
  755. 'created' => new DateTime('2016-01-01 00:00'),
  756. ],
  757. 'ArticlesTags' => ['article_id' => 1, 'tag_id' => 2],
  758. ],
  759. ],
  760. ];
  761. $this->assertEquals($expected, $results);
  762. }
  763. /**
  764. * Tests that it is possible to filter by deep associations
  765. */
  766. public function testMatchingDotNotation(): void
  767. {
  768. $query = new Query($this->connection, $this->table);
  769. $table = $this->getTableLocator()->get('authors');
  770. $this->getTableLocator()->get('articles');
  771. $table->hasMany('articles');
  772. $this->getTableLocator()->get('articles')->belongsToMany('tags');
  773. $results = $query->setRepository($table)
  774. ->select()
  775. ->enableHydration(false)
  776. ->matching('articles.tags', function ($q) {
  777. return $q->where(['tags.id' => 2]);
  778. })
  779. ->toArray();
  780. $expected = [
  781. [
  782. 'id' => 1,
  783. 'name' => 'mariano',
  784. '_matchingData' => [
  785. 'tags' => [
  786. 'id' => 2,
  787. 'name' => 'tag2',
  788. 'description' => 'Another big description',
  789. 'created' => new DateTime('2016-01-01 00:00'),
  790. ],
  791. 'articles' => [
  792. 'id' => 1,
  793. 'author_id' => 1,
  794. 'title' => 'First Article',
  795. 'body' => 'First Article Body',
  796. 'published' => 'Y',
  797. ],
  798. 'ArticlesTags' => [
  799. 'article_id' => 1,
  800. 'tag_id' => 2,
  801. ],
  802. ],
  803. ],
  804. ];
  805. $this->assertEquals($expected, $results);
  806. }
  807. /**
  808. * Test setResult()
  809. */
  810. public function testSetResult(): void
  811. {
  812. $query = new Query($this->connection, $this->table);
  813. $results = new ResultSet([]);
  814. $query->setResult($results);
  815. $this->assertSame($results, $query->all());
  816. $query->setResult([]);
  817. $this->assertInstanceOf(ResultSetDecorator::class, $query->all());
  818. }
  819. /**
  820. * Test clearResult()
  821. */
  822. public function testClearResult(): void
  823. {
  824. $article = $this->getTableLocator()->get('articles');
  825. $query = new Query($this->connection, $article);
  826. $firstCount = $query->count();
  827. $firstResults = $query->toArray();
  828. $this->assertEquals(3, $firstCount);
  829. $this->assertCount(3, $firstResults);
  830. $article->delete(reset($firstResults));
  831. $return = $query->clearResult();
  832. $this->assertSame($return, $query);
  833. $secondCount = $query->count();
  834. $secondResults = $query->toArray();
  835. $this->assertEquals(2, $secondCount);
  836. $this->assertCount(2, $secondResults);
  837. }
  838. /**
  839. * Tests that applying array options to a query will convert them
  840. * to equivalent function calls with the correspondent array values
  841. */
  842. public function testApplyOptions(): void
  843. {
  844. $this->table->belongsTo('articles');
  845. $typeMap = new TypeMap([
  846. 'foo.id' => 'integer',
  847. 'id' => 'integer',
  848. 'foo__id' => 'integer',
  849. 'articles.id' => 'integer',
  850. 'articles__id' => 'integer',
  851. 'articles.author_id' => 'integer',
  852. 'articles__author_id' => 'integer',
  853. 'author_id' => 'integer',
  854. 'articles.title' => 'string',
  855. 'articles__title' => 'string',
  856. 'title' => 'string',
  857. 'articles.body' => 'text',
  858. 'articles__body' => 'text',
  859. 'body' => 'text',
  860. 'articles.published' => 'string',
  861. 'articles__published' => 'string',
  862. 'published' => 'string',
  863. ]);
  864. $options = [
  865. 'fields' => ['field_a', 'field_b'],
  866. 'conditions' => ['field_a' => 1, 'field_b' => 'something'],
  867. 'limit' => 1,
  868. 'order' => ['a' => 'ASC'],
  869. 'offset' => 5,
  870. 'group' => ['field_a'],
  871. 'having' => ['field_a >' => 100],
  872. 'contain' => ['articles'],
  873. 'join' => ['table_a' => ['conditions' => ['a > b']]],
  874. ];
  875. $query = new Query($this->connection, $this->table);
  876. $query->applyOptions($options);
  877. $this->assertEquals(['field_a', 'field_b'], $query->clause('select'));
  878. $expected = new QueryExpression($options['conditions'], $typeMap);
  879. $result = $query->clause('where');
  880. $this->assertEquals($expected, $result);
  881. $this->assertEquals(1, $query->clause('limit'));
  882. $expected = new QueryExpression(['a > b'], $typeMap);
  883. $result = $query->clause('join');
  884. $this->assertEquals([
  885. 'table_a' => ['alias' => 'table_a', 'type' => 'INNER', 'conditions' => $expected],
  886. ], $result);
  887. $expected = new OrderByExpression(['a' => 'ASC']);
  888. $this->assertEquals($expected, $query->clause('order'));
  889. $this->assertEquals(5, $query->clause('offset'));
  890. $this->assertEquals(['field_a'], $query->clause('group'));
  891. $expected = new QueryExpression($options['having'], $typeMap);
  892. $this->assertEquals($expected, $query->clause('having'));
  893. $expected = ['articles' => []];
  894. $this->assertEquals($expected, $query->getContain());
  895. }
  896. /**
  897. * Test that page is applied after limit.
  898. */
  899. public function testApplyOptionsPageIsLast(): void
  900. {
  901. $query = new Query($this->connection, $this->table);
  902. $opts = [
  903. 'page' => 3,
  904. 'limit' => 5,
  905. ];
  906. $query->applyOptions($opts);
  907. $this->assertEquals(5, $query->clause('limit'));
  908. $this->assertEquals(10, $query->clause('offset'));
  909. }
  910. /**
  911. * ApplyOptions should ignore null values.
  912. */
  913. public function testApplyOptionsIgnoreNull(): void
  914. {
  915. $options = [
  916. 'fields' => null,
  917. ];
  918. $query = new Query($this->connection, $this->table);
  919. $query->applyOptions($options);
  920. $this->assertEquals([], $query->clause('select'));
  921. }
  922. /**
  923. * Tests getOptions() method
  924. */
  925. public function testGetOptions(): void
  926. {
  927. $options = ['doABarrelRoll' => true, 'fields' => ['id', 'name']];
  928. $query = new Query($this->connection, $this->table);
  929. $query->applyOptions($options);
  930. $expected = ['doABarrelRoll' => true];
  931. $this->assertEquals($expected, $query->getOptions());
  932. $expected = ['doABarrelRoll' => false, 'doAwesome' => true];
  933. $query->applyOptions($expected);
  934. $this->assertEquals($expected, $query->getOptions());
  935. }
  936. /**
  937. * Tests registering mappers with mapReduce()
  938. */
  939. public function testMapReduceOnlyMapper(): void
  940. {
  941. $mapper1 = function (): void {
  942. };
  943. $mapper2 = function (): void {
  944. };
  945. $query = new Query($this->connection, $this->table);
  946. $this->assertSame($query, $query->mapReduce($mapper1));
  947. $this->assertEquals(
  948. [['mapper' => $mapper1, 'reducer' => null]],
  949. $query->getMapReducers()
  950. );
  951. $this->assertEquals($query, $query->mapReduce($mapper2));
  952. $result = $query->getMapReducers();
  953. $this->assertSame(
  954. [
  955. ['mapper' => $mapper1, 'reducer' => null],
  956. ['mapper' => $mapper2, 'reducer' => null],
  957. ],
  958. $result
  959. );
  960. }
  961. /**
  962. * Tests registering mappers and reducers with mapReduce()
  963. */
  964. public function testMapReduceBothMethods(): void
  965. {
  966. $mapper1 = function (): void {
  967. };
  968. $mapper2 = function (): void {
  969. };
  970. $reducer1 = function (): void {
  971. };
  972. $reducer2 = function (): void {
  973. };
  974. $query = new Query($this->connection, $this->table);
  975. $this->assertSame($query, $query->mapReduce($mapper1, $reducer1));
  976. $this->assertEquals(
  977. [['mapper' => $mapper1, 'reducer' => $reducer1]],
  978. $query->getMapReducers()
  979. );
  980. $this->assertSame($query, $query->mapReduce($mapper2, $reducer2));
  981. $this->assertEquals(
  982. [
  983. ['mapper' => $mapper1, 'reducer' => $reducer1],
  984. ['mapper' => $mapper2, 'reducer' => $reducer2],
  985. ],
  986. $query->getMapReducers()
  987. );
  988. }
  989. /**
  990. * Tests that it is possible to overwrite previous map reducers
  991. */
  992. public function testOverwriteMapReduce(): void
  993. {
  994. $mapper1 = function (): void {
  995. };
  996. $mapper2 = function (): void {
  997. };
  998. $reducer1 = function (): void {
  999. };
  1000. $reducer2 = function (): void {
  1001. };
  1002. $query = new Query($this->connection, $this->table);
  1003. $this->assertEquals($query, $query->mapReduce($mapper1, $reducer1));
  1004. $this->assertEquals(
  1005. [['mapper' => $mapper1, 'reducer' => $reducer1]],
  1006. $query->getMapReducers()
  1007. );
  1008. $this->assertEquals($query, $query->mapReduce($mapper2, $reducer2, true));
  1009. $this->assertEquals(
  1010. [['mapper' => $mapper2, 'reducer' => $reducer2]],
  1011. $query->getMapReducers()
  1012. );
  1013. }
  1014. /**
  1015. * Tests that multiple map reducers can be stacked
  1016. */
  1017. public function testResultsAreWrappedInMapReduce(): void
  1018. {
  1019. $table = $this->getTableLocator()->get('articles', ['table' => 'articles']);
  1020. $query = new Query($this->connection, $table);
  1021. $query->select(['a' => 'id'])->limit(2)->order(['id' => 'ASC']);
  1022. $query->mapReduce(function ($v, $k, $mr): void {
  1023. $mr->emit($v['a']);
  1024. });
  1025. $query->mapReduce(
  1026. function ($v, $k, $mr): void {
  1027. $mr->emitIntermediate($v, $k);
  1028. },
  1029. function ($v, $k, $mr): void {
  1030. $mr->emit($v[0] + 1);
  1031. }
  1032. );
  1033. $this->assertEquals([2, 3], iterator_to_array($query->all()));
  1034. }
  1035. /**
  1036. * Tests first() method when the query has not been executed before
  1037. */
  1038. public function testFirstDirtyQuery(): void
  1039. {
  1040. $table = $this->getTableLocator()->get('articles', ['table' => 'articles']);
  1041. $query = new Query($this->connection, $table);
  1042. $result = $query->select(['id'])->enableHydration(false)->first();
  1043. $this->assertEquals(['id' => 1], $result);
  1044. $this->assertEquals(1, $query->clause('limit'));
  1045. $result = $query->select(['id'])->first();
  1046. $this->assertEquals(['id' => 1], $result);
  1047. }
  1048. /**
  1049. * Tests that first can be called again on an already executed query
  1050. */
  1051. public function testFirstCleanQuery(): void
  1052. {
  1053. $table = $this->getTableLocator()->get('articles', ['table' => 'articles']);
  1054. $query = new Query($this->connection, $table);
  1055. $query->select(['id'])->toArray();
  1056. $first = $query->enableHydration(false)->first();
  1057. $this->assertEquals(['id' => 1], $first);
  1058. $this->assertEquals(1, $query->clause('limit'));
  1059. }
  1060. /**
  1061. * Tests that first() will not execute the same query twice
  1062. */
  1063. public function testFirstSameResult(): void
  1064. {
  1065. $table = $this->getTableLocator()->get('articles', ['table' => 'articles']);
  1066. $query = new Query($this->connection, $table);
  1067. $query->select(['id'])->toArray();
  1068. $first = $query->enableHydration(false)->first();
  1069. $resultSet = $query->all();
  1070. $this->assertEquals(['id' => 1], $first);
  1071. $this->assertSame($resultSet, $query->all());
  1072. }
  1073. /**
  1074. * Tests that first can be called against a query with a mapReduce
  1075. */
  1076. public function testFirstMapReduce(): void
  1077. {
  1078. $map = function ($row, $key, $mapReduce): void {
  1079. $mapReduce->emitIntermediate($row['id'], 'id');
  1080. };
  1081. $reduce = function ($values, $key, $mapReduce): void {
  1082. $mapReduce->emit(array_sum($values));
  1083. };
  1084. $table = $this->getTableLocator()->get('articles', ['table' => 'articles']);
  1085. $query = new Query($this->connection, $table);
  1086. $query->select(['id'])
  1087. ->enableHydration(false)
  1088. ->mapReduce($map, $reduce);
  1089. $first = $query->first();
  1090. $this->assertEquals(1, $first);
  1091. }
  1092. /**
  1093. * Tests that first can be called on an unbuffered query
  1094. */
  1095. public function testFirstUnbuffered(): void
  1096. {
  1097. $table = $this->getTableLocator()->get('Articles');
  1098. $query = new Query($this->connection, $table);
  1099. $query->select(['id']);
  1100. $first = $query->enableHydration(false)->first();
  1101. $this->assertEquals(['id' => 1], $first);
  1102. }
  1103. /**
  1104. * Testing hydrating a result set into Entity objects
  1105. */
  1106. public function testHydrateSimple(): void
  1107. {
  1108. $table = $this->getTableLocator()->get('articles', ['table' => 'articles']);
  1109. $query = new Query($this->connection, $table);
  1110. $results = $query->select()->toArray();
  1111. $this->assertCount(3, $results);
  1112. foreach ($results as $r) {
  1113. $this->assertInstanceOf('Cake\ORM\Entity', $r);
  1114. }
  1115. $first = $results[0];
  1116. $this->assertEquals(1, $first->id);
  1117. $this->assertEquals(1, $first->author_id);
  1118. $this->assertSame('First Article', $first->title);
  1119. $this->assertSame('First Article Body', $first->body);
  1120. $this->assertSame('Y', $first->published);
  1121. }
  1122. /**
  1123. * Tests that has many results are also hydrated correctly
  1124. */
  1125. public function testHydrateHasMany(): void
  1126. {
  1127. $table = $this->getTableLocator()->get('authors');
  1128. $this->getTableLocator()->get('articles');
  1129. $table->hasMany('articles', [
  1130. 'propertyName' => 'articles',
  1131. 'sort' => ['articles.id' => 'asc'],
  1132. ]);
  1133. $query = new Query($this->connection, $table);
  1134. $results = $query->select()
  1135. ->contain('articles')
  1136. ->toArray();
  1137. $first = $results[0];
  1138. foreach ($first->articles as $r) {
  1139. $this->assertInstanceOf('Cake\ORM\Entity', $r);
  1140. }
  1141. $this->assertCount(2, $first->articles);
  1142. $expected = [
  1143. 'id' => 1,
  1144. 'title' => 'First Article',
  1145. 'body' => 'First Article Body',
  1146. 'author_id' => 1,
  1147. 'published' => 'Y',
  1148. ];
  1149. $this->assertEquals($expected, $first->articles[0]->toArray());
  1150. $expected = [
  1151. 'id' => 3,
  1152. 'title' => 'Third Article',
  1153. 'author_id' => 1,
  1154. 'body' => 'Third Article Body',
  1155. 'published' => 'Y',
  1156. ];
  1157. $this->assertEquals($expected, $first->articles[1]->toArray());
  1158. }
  1159. /**
  1160. * Tests that belongsToMany associations are also correctly hydrated
  1161. */
  1162. public function testHydrateBelongsToMany(): void
  1163. {
  1164. $table = $this->getTableLocator()->get('Articles');
  1165. $this->getTableLocator()->get('Tags');
  1166. $this->getTableLocator()->get('ArticlesTags', [
  1167. 'table' => 'articles_tags',
  1168. ]);
  1169. $table->belongsToMany('Tags');
  1170. $query = new Query($this->connection, $table);
  1171. $results = $query
  1172. ->select()
  1173. ->contain('Tags')
  1174. ->toArray();
  1175. $first = $results[0];
  1176. foreach ($first->tags as $r) {
  1177. $this->assertInstanceOf('Cake\ORM\Entity', $r);
  1178. }
  1179. $this->assertCount(2, $first->tags);
  1180. $expected = [
  1181. 'id' => 1,
  1182. 'name' => 'tag1',
  1183. '_joinData' => ['article_id' => 1, 'tag_id' => 1],
  1184. 'description' => 'A big description',
  1185. 'created' => new DateTime('2016-01-01 00:00'),
  1186. ];
  1187. $this->assertEquals($expected, $first->tags[0]->toArray());
  1188. $this->assertInstanceOf(DateTime::class, $first->tags[0]->created);
  1189. $expected = [
  1190. 'id' => 2,
  1191. 'name' => 'tag2',
  1192. '_joinData' => ['article_id' => 1, 'tag_id' => 2],
  1193. 'description' => 'Another big description',
  1194. 'created' => new DateTime('2016-01-01 00:00'),
  1195. ];
  1196. $this->assertEquals($expected, $first->tags[1]->toArray());
  1197. $this->assertInstanceOf(DateTime::class, $first->tags[1]->created);
  1198. }
  1199. /**
  1200. * Tests that belongsToMany associations are also correctly hydrated
  1201. */
  1202. public function testFormatResultsBelongsToMany(): void
  1203. {
  1204. $table = $this->getTableLocator()->get('Articles');
  1205. $this->getTableLocator()->get('Tags');
  1206. $articlesTags = $this->getTableLocator()->get('ArticlesTags', [
  1207. 'table' => 'articles_tags',
  1208. ]);
  1209. $table->belongsToMany('Tags');
  1210. $articlesTags
  1211. ->getEventManager()
  1212. ->on('Model.beforeFind', function (EventInterface $event, $query): void {
  1213. $query->formatResults(function ($results) {
  1214. foreach ($results as $result) {
  1215. $result->beforeFind = true;
  1216. }
  1217. return $results;
  1218. });
  1219. });
  1220. $query = new Query($this->connection, $table);
  1221. $results = $query
  1222. ->select()
  1223. ->contain('Tags')
  1224. ->toArray();
  1225. $first = $results[0];
  1226. foreach ($first->tags as $r) {
  1227. $this->assertInstanceOf('Cake\ORM\Entity', $r);
  1228. }
  1229. $this->assertCount(2, $first->tags);
  1230. $expected = [
  1231. 'id' => 1,
  1232. 'name' => 'tag1',
  1233. '_joinData' => [
  1234. 'article_id' => 1,
  1235. 'tag_id' => 1,
  1236. 'beforeFind' => true,
  1237. ],
  1238. 'description' => 'A big description',
  1239. 'created' => new DateTime('2016-01-01 00:00'),
  1240. ];
  1241. $this->assertEquals($expected, $first->tags[0]->toArray());
  1242. $this->assertInstanceOf(DateTime::class, $first->tags[0]->created);
  1243. $expected = [
  1244. 'id' => 2,
  1245. 'name' => 'tag2',
  1246. '_joinData' => [
  1247. 'article_id' => 1,
  1248. 'tag_id' => 2,
  1249. 'beforeFind' => true,
  1250. ],
  1251. 'description' => 'Another big description',
  1252. 'created' => new DateTime('2016-01-01 00:00'),
  1253. ];
  1254. $this->assertEquals($expected, $first->tags[1]->toArray());
  1255. $this->assertInstanceOf(DateTime::class, $first->tags[0]->created);
  1256. }
  1257. /**
  1258. * Tests that belongsTo relations are correctly hydrated
  1259. *
  1260. * @dataProvider strategiesProviderBelongsTo
  1261. */
  1262. public function testHydrateBelongsTo(string $strategy): void
  1263. {
  1264. $table = $this->getTableLocator()->get('articles');
  1265. $this->getTableLocator()->get('authors');
  1266. $table->belongsTo('authors', ['strategy' => $strategy]);
  1267. $query = new Query($this->connection, $table);
  1268. $results = $query->select()
  1269. ->contain('authors')
  1270. ->order(['articles.id' => 'asc'])
  1271. ->toArray();
  1272. $this->assertCount(3, $results);
  1273. $first = $results[0];
  1274. $this->assertInstanceOf('Cake\ORM\Entity', $first->author);
  1275. $expected = ['id' => 1, 'name' => 'mariano'];
  1276. $this->assertEquals($expected, $first->author->toArray());
  1277. }
  1278. /**
  1279. * Tests that deeply nested associations are also hydrated correctly
  1280. *
  1281. * @dataProvider strategiesProviderBelongsTo
  1282. */
  1283. public function testHydrateDeep(string $strategy): void
  1284. {
  1285. $table = $this->getTableLocator()->get('authors');
  1286. $article = $this->getTableLocator()->get('articles');
  1287. $table->hasMany('articles', [
  1288. 'propertyName' => 'articles',
  1289. 'sort' => ['articles.id' => 'asc'],
  1290. ]);
  1291. $article->belongsTo('authors', ['strategy' => $strategy]);
  1292. $query = new Query($this->connection, $table);
  1293. $results = $query->select()
  1294. ->contain(['articles' => ['authors']])
  1295. ->toArray();
  1296. $this->assertCount(4, $results);
  1297. $first = $results[0];
  1298. $this->assertInstanceOf('Cake\ORM\Entity', $first->articles[0]->author);
  1299. $expected = ['id' => 1, 'name' => 'mariano'];
  1300. $this->assertEquals($expected, $first->articles[0]->author->toArray());
  1301. $this->assertTrue(isset($results[3]->articles));
  1302. }
  1303. /**
  1304. * Tests that it is possible to use a custom entity class
  1305. */
  1306. public function testHydrateCustomObject(): void
  1307. {
  1308. $class = $this->getMockClass('Cake\ORM\Entity', ['fakeMethod']);
  1309. $table = $this->getTableLocator()->get('articles', [
  1310. 'table' => 'articles',
  1311. 'entityClass' => '\\' . $class,
  1312. ]);
  1313. $query = new Query($this->connection, $table);
  1314. $results = $query->select()->toArray();
  1315. $this->assertCount(3, $results);
  1316. foreach ($results as $r) {
  1317. $this->assertInstanceOf($class, $r);
  1318. }
  1319. $first = $results[0];
  1320. $this->assertEquals(1, $first->id);
  1321. $this->assertEquals(1, $first->author_id);
  1322. $this->assertSame('First Article', $first->title);
  1323. $this->assertSame('First Article Body', $first->body);
  1324. $this->assertSame('Y', $first->published);
  1325. }
  1326. /**
  1327. * Tests that has many results are also hydrated correctly
  1328. * when specified a custom entity class
  1329. */
  1330. public function testHydrateHasManyCustomEntity(): void
  1331. {
  1332. $authorEntity = $this->getMockClass('Cake\ORM\Entity', ['foo']);
  1333. $articleEntity = $this->getMockClass('Cake\ORM\Entity', ['foo']);
  1334. $table = $this->getTableLocator()->get('authors', [
  1335. 'entityClass' => '\\' . $authorEntity,
  1336. ]);
  1337. $this->getTableLocator()->get('articles', [
  1338. 'entityClass' => '\\' . $articleEntity,
  1339. ]);
  1340. $table->hasMany('articles', [
  1341. 'propertyName' => 'articles',
  1342. 'sort' => ['articles.id' => 'asc'],
  1343. ]);
  1344. $query = new Query($this->connection, $table);
  1345. $results = $query->select()
  1346. ->contain('articles')
  1347. ->toArray();
  1348. $first = $results[0];
  1349. $this->assertInstanceOf($authorEntity, $first);
  1350. foreach ($first->articles as $r) {
  1351. $this->assertInstanceOf($articleEntity, $r);
  1352. }
  1353. $this->assertCount(2, $first->articles);
  1354. $expected = [
  1355. 'id' => 1,
  1356. 'title' => 'First Article',
  1357. 'body' => 'First Article Body',
  1358. 'author_id' => 1,
  1359. 'published' => 'Y',
  1360. ];
  1361. $this->assertEquals($expected, $first->articles[0]->toArray());
  1362. }
  1363. /**
  1364. * Tests that belongsTo relations are correctly hydrated into a custom entity class
  1365. */
  1366. public function testHydrateBelongsToCustomEntity(): void
  1367. {
  1368. $authorEntity = $this->getMockClass('Cake\ORM\Entity', ['foo']);
  1369. $table = $this->getTableLocator()->get('articles');
  1370. $this->getTableLocator()->get('authors', [
  1371. 'entityClass' => '\\' . $authorEntity,
  1372. ]);
  1373. $table->belongsTo('authors');
  1374. $query = new Query($this->connection, $table);
  1375. $results = $query->select()
  1376. ->contain('authors')
  1377. ->order(['articles.id' => 'asc'])
  1378. ->toArray();
  1379. $first = $results[0];
  1380. $this->assertInstanceOf($authorEntity, $first->author);
  1381. }
  1382. /**
  1383. * Test getting counts from queries.
  1384. */
  1385. public function testCount(): void
  1386. {
  1387. $table = $this->getTableLocator()->get('articles');
  1388. $result = $table->find('all')->count();
  1389. $this->assertSame(3, $result);
  1390. $query = $table->find('all')
  1391. ->where(['id >' => 1])
  1392. ->limit(1);
  1393. $result = $query->count();
  1394. $this->assertSame(2, $result);
  1395. $result = $query->all();
  1396. $this->assertCount(1, $result);
  1397. $this->assertEquals(2, $result->first()->id);
  1398. }
  1399. /**
  1400. * Test getting counts from queries with contain.
  1401. */
  1402. public function testCountWithContain(): void
  1403. {
  1404. $table = $this->getTableLocator()->get('Articles');
  1405. $table->belongsTo('Authors');
  1406. $result = $table->find('all')
  1407. ->contain([
  1408. 'Authors' => [
  1409. 'fields' => ['name'],
  1410. ],
  1411. ])
  1412. ->count();
  1413. $this->assertSame(3, $result);
  1414. }
  1415. /**
  1416. * Test getting counts from queries with contain.
  1417. */
  1418. public function testCountWithSubselect(): void
  1419. {
  1420. $table = $this->getTableLocator()->get('Articles');
  1421. $table->belongsTo('Authors');
  1422. $table->hasMany('ArticlesTags');
  1423. $counter = $table->ArticlesTags->find();
  1424. $counter->select([
  1425. 'total' => $counter->func()->count('*'),
  1426. ])
  1427. ->where([
  1428. 'ArticlesTags.tag_id' => 1,
  1429. 'ArticlesTags.article_id' => new IdentifierExpression('Articles.id'),
  1430. ]);
  1431. $result = $table->find('all')
  1432. ->select([
  1433. 'Articles.title',
  1434. 'tag_count' => $counter,
  1435. ])
  1436. ->matching('Authors', function ($q) {
  1437. return $q->where(['Authors.id' => 1]);
  1438. })
  1439. ->count();
  1440. $this->assertSame(2, $result);
  1441. }
  1442. /**
  1443. * Test getting counts with complex fields.
  1444. */
  1445. public function testCountWithExpressions(): void
  1446. {
  1447. $table = $this->getTableLocator()->get('Articles');
  1448. $query = $table->find();
  1449. $query->select([
  1450. 'title' => $query->func()->concat(
  1451. ['title' => 'identifier', 'test'],
  1452. ['string']
  1453. ),
  1454. ]);
  1455. $query->where(['id' => 1]);
  1456. $this->assertCount(1, $query->all());
  1457. $this->assertEquals(1, $query->count());
  1458. }
  1459. /**
  1460. * test count with a beforeFind.
  1461. */
  1462. public function testCountBeforeFind(): void
  1463. {
  1464. $table = $this->getTableLocator()->get('Articles');
  1465. $table->hasMany('Comments');
  1466. $table->getEventManager()
  1467. ->on('Model.beforeFind', function (EventInterface $event, $query): void {
  1468. $query
  1469. ->limit(1)
  1470. ->order(['Articles.title' => 'DESC']);
  1471. });
  1472. $query = $table->find();
  1473. $result = $query->count();
  1474. $this->assertSame(3, $result);
  1475. }
  1476. /**
  1477. * Tests that beforeFind is only ever called once, even if you trigger it again in the beforeFind
  1478. */
  1479. public function testBeforeFindCalledOnce(): void
  1480. {
  1481. $callCount = 0;
  1482. $table = $this->getTableLocator()->get('Articles');
  1483. $table->getEventManager()
  1484. ->on('Model.beforeFind', function (EventInterface $event, $query) use (&$callCount): void {
  1485. $valueBinder = new ValueBinder();
  1486. $query->sql($valueBinder);
  1487. $callCount++;
  1488. });
  1489. $query = $table->find();
  1490. $valueBinder = new ValueBinder();
  1491. $query->sql($valueBinder);
  1492. $this->assertSame(1, $callCount);
  1493. }
  1494. /**
  1495. * Test that count() returns correct results with group by.
  1496. */
  1497. public function testCountWithGroup(): void
  1498. {
  1499. $table = $this->getTableLocator()->get('articles');
  1500. $query = $table->find('all');
  1501. $query->select(['author_id', 's' => $query->func()->sum('id')])
  1502. ->group(['author_id']);
  1503. $result = $query->count();
  1504. $this->assertEquals(2, $result);
  1505. }
  1506. /**
  1507. * Tests that it is possible to provide a callback for calculating the count
  1508. * of a query
  1509. */
  1510. public function testCountWithCustomCounter(): void
  1511. {
  1512. $table = $this->getTableLocator()->get('articles');
  1513. $query = $table->find('all');
  1514. $query
  1515. ->select(['author_id', 's' => $query->func()->sum('id')])
  1516. ->where(['id >' => 2])
  1517. ->group(['author_id'])
  1518. ->counter(function ($q) use ($query) {
  1519. $this->assertNotSame($q, $query);
  1520. return $q->select([], true)->group([], true)->count();
  1521. });
  1522. $result = $query->count();
  1523. $this->assertEquals(1, $result);
  1524. }
  1525. /**
  1526. * Test that RAND() returns correct results.
  1527. */
  1528. public function testSelectRandom(): void
  1529. {
  1530. $table = $this->getTableLocator()->get('articles');
  1531. $query = $table
  1532. ->query();
  1533. $query->select(['s' => $query->func()->rand()]);
  1534. $result = $query
  1535. ->all()
  1536. ->extract('s')
  1537. ->first();
  1538. $this->assertGreaterThanOrEqual(0, $result);
  1539. $this->assertLessThan(1, $result);
  1540. }
  1541. /**
  1542. * Test update method.
  1543. */
  1544. public function testUpdate(): void
  1545. {
  1546. $table = $this->getTableLocator()->get('articles');
  1547. $result = $table->updateQuery()
  1548. ->set(['title' => 'First'])
  1549. ->execute();
  1550. $this->assertInstanceOf(StatementInterface::class, $result);
  1551. $this->assertGreaterThan(0, $result->rowCount());
  1552. }
  1553. /**
  1554. * Test update method.
  1555. */
  1556. public function testUpdateWithTableExpression(): void
  1557. {
  1558. $this->skipIf(!$this->connection->getDriver() instanceof Mysql);
  1559. $table = $this->getTableLocator()->get('articles');
  1560. $query = $table->updateQuery();
  1561. $result = $query->update($query->newExpr('articles, authors'))
  1562. ->set(['title' => 'First'])
  1563. ->where(['articles.author_id = authors.id'])
  1564. ->andWhere(['authors.name' => 'mariano'])
  1565. ->execute();
  1566. $this->assertInstanceOf(StatementInterface::class, $result);
  1567. $this->assertGreaterThan(0, $result->rowCount());
  1568. }
  1569. /**
  1570. * Test insert method.
  1571. */
  1572. public function testInsert(): void
  1573. {
  1574. $table = $this->getTableLocator()->get('articles');
  1575. $result = $table->insertQuery()
  1576. ->insert(['title'])
  1577. ->values(['title' => 'First'])
  1578. ->values(['title' => 'Second'])
  1579. ->execute();
  1580. $result->closeCursor();
  1581. $this->assertInstanceOf(StatementInterface::class, $result);
  1582. $this->assertEquals(2, $result->rowCount());
  1583. }
  1584. /**
  1585. * Test delete method.
  1586. */
  1587. public function testDelete(): void
  1588. {
  1589. $table = $this->getTableLocator()->get('articles');
  1590. $result = $table->deleteQuery()
  1591. ->where(['id >=' => 1])
  1592. ->execute();
  1593. $this->assertInstanceOf(StatementInterface::class, $result);
  1594. $this->assertGreaterThan(0, $result->rowCount());
  1595. }
  1596. /**
  1597. * testClearContain
  1598. */
  1599. public function testClearContain(): void
  1600. {
  1601. /** @var \Cake\ORM\Query $query */
  1602. $query = $this->getMockBuilder('Cake\ORM\Query')
  1603. ->onlyMethods(['all'])
  1604. ->setConstructorArgs([$this->connection, $this->table])
  1605. ->getMock();
  1606. $query->contain([
  1607. 'Articles',
  1608. ]);
  1609. $result = $query->getContain();
  1610. $this->assertIsArray($result);
  1611. $this->assertNotEmpty($result);
  1612. $result = $query->clearContain();
  1613. $this->assertInstanceOf(Query::class, $result);
  1614. $result = $query->getContain();
  1615. $this->assertIsArray($result);
  1616. $this->assertEmpty($result);
  1617. }
  1618. /**
  1619. * Integration test for query caching.
  1620. */
  1621. public function testCacheReadIntegration(): void
  1622. {
  1623. $query = $this->getMockBuilder('Cake\ORM\Query')
  1624. ->onlyMethods(['execute'])
  1625. ->setConstructorArgs([$this->connection, $this->table])
  1626. ->getMock();
  1627. $resultSet = new ResultSet([]);
  1628. $query->expects($this->never())
  1629. ->method('execute');
  1630. $cacher = $this->getMockBuilder('Cake\Cache\CacheEngine')->getMock();
  1631. $cacher->expects($this->once())
  1632. ->method('get')
  1633. ->with('my_key')
  1634. ->will($this->returnValue($resultSet));
  1635. $query->cache('my_key', $cacher)
  1636. ->where(['id' => 1]);
  1637. $results = $query->all();
  1638. $this->assertSame($resultSet, $results);
  1639. }
  1640. /**
  1641. * Integration test for query caching.
  1642. */
  1643. public function testCacheWriteIntegration(): void
  1644. {
  1645. $table = $this->getTableLocator()->get('Articles');
  1646. $query = new Query($this->connection, $table);
  1647. $query->select(['id', 'title']);
  1648. $cacher = $this->getMockBuilder('Cake\Cache\CacheEngine')->getMock();
  1649. $cacher->expects($this->once())
  1650. ->method('set')
  1651. ->with(
  1652. 'my_key',
  1653. $this->isInstanceOf('Cake\Datasource\ResultSetInterface')
  1654. );
  1655. $query->cache('my_key', $cacher)
  1656. ->where(['id' => 1]);
  1657. $query->all();
  1658. }
  1659. /**
  1660. * Integration test for query caching using a real cache engine and
  1661. * a formatResults callback
  1662. */
  1663. public function testCacheIntegrationWithFormatResults(): void
  1664. {
  1665. $table = $this->getTableLocator()->get('Articles');
  1666. $query = new Query($this->connection, $table);
  1667. $cacher = new FileEngine();
  1668. $cacher->init();
  1669. $query
  1670. ->select(['id', 'title'])
  1671. ->formatResults(function ($results) {
  1672. return $results->combine('id', 'title');
  1673. })
  1674. ->cache('my_key', $cacher);
  1675. $expected = $query->toArray();
  1676. $query = new Query($this->connection, $table);
  1677. $results = $query->cache('my_key', $cacher)->toArray();
  1678. $this->assertSame($expected, $results);
  1679. }
  1680. /**
  1681. * Test overwriting the contained associations.
  1682. */
  1683. public function testContainOverwrite(): void
  1684. {
  1685. $table = $this->getTableLocator()->get('Articles');
  1686. $table->hasMany('Comments');
  1687. $table->belongsTo('Authors');
  1688. $query = $table->find();
  1689. $query->contain(['Comments']);
  1690. $this->assertEquals(['Comments'], array_keys($query->getContain()));
  1691. $query->contain(['Authors'], true);
  1692. $this->assertEquals(['Authors'], array_keys($query->getContain()));
  1693. $query->contain(['Comments', 'Authors'], true);
  1694. $this->assertEquals(['Comments', 'Authors'], array_keys($query->getContain()));
  1695. }
  1696. /**
  1697. * Integration test to show filtering associations using contain and a closure
  1698. */
  1699. public function testContainWithClosure(): void
  1700. {
  1701. $table = $this->getTableLocator()->get('authors');
  1702. $table->hasMany('articles');
  1703. $query = new Query($this->connection, $table);
  1704. $query
  1705. ->select()
  1706. ->contain([
  1707. 'articles' => function ($q) {
  1708. return $q->where(['articles.id' => 1]);
  1709. },
  1710. ]);
  1711. $ids = [];
  1712. foreach ($query as $entity) {
  1713. foreach ((array)$entity->articles as $article) {
  1714. $ids[] = $article->id;
  1715. }
  1716. }
  1717. $this->assertEquals([1], array_unique($ids));
  1718. }
  1719. /**
  1720. * Integration test that uses the contain signature that is the same as the
  1721. * matching signature
  1722. */
  1723. public function testContainClosureSignature(): void
  1724. {
  1725. $table = $this->getTableLocator()->get('authors');
  1726. $table->hasMany('articles');
  1727. $query = new Query($this->connection, $table);
  1728. $query
  1729. ->select()
  1730. ->contain('articles', function ($q) {
  1731. return $q->where(['articles.id' => 1]);
  1732. });
  1733. $ids = [];
  1734. foreach ($query as $entity) {
  1735. foreach ((array)$entity->articles as $article) {
  1736. $ids[] = $article->id;
  1737. }
  1738. }
  1739. $this->assertEquals([1], array_unique($ids));
  1740. }
  1741. public function testContainAutoFields(): void
  1742. {
  1743. $table = $this->getTableLocator()->get('authors');
  1744. $table->hasMany('articles');
  1745. $query = new Query($this->connection, $table);
  1746. $query
  1747. ->select()
  1748. ->contain('articles', function ($q) {
  1749. return $q->select(['test' => '(SELECT 20)'])
  1750. ->enableAutoFields(true);
  1751. });
  1752. $results = $query->toArray();
  1753. $this->assertNotEmpty($results);
  1754. }
  1755. /**
  1756. * Integration test to ensure that filtering associations with the queryBuilder
  1757. * option works.
  1758. */
  1759. public function testContainWithQueryBuilderHasManyError(): void
  1760. {
  1761. $this->expectException(DatabaseException::class);
  1762. $table = $this->getTableLocator()->get('Authors');
  1763. $table->hasMany('Articles');
  1764. $query = new Query($this->connection, $table);
  1765. $query->select()
  1766. ->contain([
  1767. 'Articles' => [
  1768. 'foreignKey' => false,
  1769. 'queryBuilder' => function ($q) {
  1770. return $q->where(['articles.id' => 1]);
  1771. },
  1772. ],
  1773. ]);
  1774. $query->toArray();
  1775. }
  1776. /**
  1777. * Integration test to ensure that filtering associations with the queryBuilder
  1778. * option works.
  1779. */
  1780. public function testContainWithQueryBuilderJoinableAssociation(): void
  1781. {
  1782. $table = $this->getTableLocator()->get('Authors');
  1783. $table->hasOne('Articles');
  1784. $query = new Query($this->connection, $table);
  1785. $query->select()
  1786. ->contain([
  1787. 'Articles' => [
  1788. 'foreignKey' => false,
  1789. 'queryBuilder' => function ($q) {
  1790. return $q->where(['Articles.id' => 1]);
  1791. },
  1792. ],
  1793. ]);
  1794. $result = $query->toArray();
  1795. $this->assertEquals(1, $result[0]->article->id);
  1796. $this->assertEquals(1, $result[1]->article->id);
  1797. $articles = $this->getTableLocator()->get('Articles');
  1798. $articles->belongsTo('Authors');
  1799. $query = new Query($this->connection, $articles);
  1800. $query->select()
  1801. ->contain([
  1802. 'Authors' => [
  1803. 'foreignKey' => false,
  1804. 'queryBuilder' => function ($q) {
  1805. return $q->where(['Authors.id' => 1]);
  1806. },
  1807. ],
  1808. ]);
  1809. $result = $query->toArray();
  1810. $this->assertEquals(1, $result[0]->author->id);
  1811. }
  1812. /**
  1813. * Test containing associations that have empty conditions.
  1814. */
  1815. public function testContainAssociationWithEmptyConditions(): void
  1816. {
  1817. $articles = $this->getTableLocator()->get('Articles');
  1818. $articles->belongsTo('Authors', [
  1819. 'conditions' => function ($exp, $query) {
  1820. return $exp;
  1821. },
  1822. ]);
  1823. $query = $articles->find('all')->contain(['Authors']);
  1824. $result = $query->toArray();
  1825. $this->assertCount(3, $result);
  1826. }
  1827. /**
  1828. * Tests the formatResults method
  1829. */
  1830. public function testFormatResults(): void
  1831. {
  1832. $callback1 = function (): void {
  1833. };
  1834. $callback2 = function (): void {
  1835. };
  1836. $table = $this->getTableLocator()->get('authors');
  1837. $query = new Query($this->connection, $table);
  1838. $this->assertSame($query, $query->formatResults($callback1));
  1839. $this->assertSame([$callback1], $query->getResultFormatters());
  1840. $this->assertSame($query, $query->formatResults($callback2));
  1841. $this->assertSame([$callback1, $callback2], $query->getResultFormatters());
  1842. $query->formatResults($callback2, true);
  1843. $this->assertSame([$callback2], $query->getResultFormatters());
  1844. $query->formatResults(null, true);
  1845. $this->assertSame([], $query->getResultFormatters());
  1846. $query->formatResults($callback1);
  1847. $query->formatResults($callback2, $query::PREPEND);
  1848. $this->assertSame([$callback2, $callback1], $query->getResultFormatters());
  1849. }
  1850. /**
  1851. * Tests that results formatters do receive the query object.
  1852. */
  1853. public function testResultFormatterReceivesTheQueryObject(): void
  1854. {
  1855. $resultFormatterQuery = null;
  1856. $query = $this->getTableLocator()->get('Authors')
  1857. ->find()
  1858. ->formatResults(function ($results, $query) use (&$resultFormatterQuery) {
  1859. $resultFormatterQuery = $query;
  1860. return $results;
  1861. });
  1862. $query->firstOrFail();
  1863. $this->assertSame($query, $resultFormatterQuery);
  1864. }
  1865. /**
  1866. * Tests that when using `beforeFind` events, results formatters for
  1867. * queries of joined associations do receive the source query, not the
  1868. * association target query.
  1869. */
  1870. public function testResultFormatterReceivesTheSourceQueryForJoinedAssociationsWhenUsingBeforeFind(): void
  1871. {
  1872. $articles = $this->getTableLocator()->get('Articles');
  1873. $authors = $articles->belongsTo('Authors');
  1874. $resultFormatterTargetQuery = null;
  1875. $resultFormatterSourceQuery = null;
  1876. $authors->getEventManager()->on(
  1877. 'Model.beforeFind',
  1878. function ($event, Query $targetQuery) use (&$resultFormatterTargetQuery, &$resultFormatterSourceQuery): void {
  1879. $resultFormatterTargetQuery = $targetQuery;
  1880. $targetQuery->formatResults(function ($results, $query) use (&$resultFormatterSourceQuery) {
  1881. $resultFormatterSourceQuery = $query;
  1882. return $results;
  1883. });
  1884. }
  1885. );
  1886. $sourceQuery = $articles
  1887. ->find()
  1888. ->contain('Authors');
  1889. $sourceQuery->firstOrFail();
  1890. $this->assertNotSame($resultFormatterTargetQuery, $resultFormatterSourceQuery);
  1891. $this->assertNotSame($sourceQuery, $resultFormatterTargetQuery);
  1892. $this->assertSame($sourceQuery, $resultFormatterSourceQuery);
  1893. }
  1894. /**
  1895. * Tests that when using `contain()` callables, results formatters for
  1896. * queries of joined associations do receive the source query, not the
  1897. * association target query.
  1898. */
  1899. public function testResultFormatterReceivesTheSourceQueryForJoinedAssociationWhenUsingContainCallables(): void
  1900. {
  1901. $articles = $this->getTableLocator()->get('Articles');
  1902. $articles->belongsTo('Authors');
  1903. $resultFormatterTargetQuery = null;
  1904. $resultFormatterSourceQuery = null;
  1905. $sourceQuery = $articles
  1906. ->find()
  1907. ->contain('Authors', function (Query $targetQuery) use (
  1908. &$resultFormatterTargetQuery,
  1909. &$resultFormatterSourceQuery
  1910. ) {
  1911. $resultFormatterTargetQuery = $targetQuery;
  1912. return $targetQuery->formatResults(function ($results, $query) use (&$resultFormatterSourceQuery) {
  1913. $resultFormatterSourceQuery = $query;
  1914. return $results;
  1915. });
  1916. });
  1917. $sourceQuery->firstOrFail();
  1918. $this->assertNotSame($resultFormatterTargetQuery, $resultFormatterSourceQuery);
  1919. $this->assertNotSame($sourceQuery, $resultFormatterTargetQuery);
  1920. $this->assertSame($sourceQuery, $resultFormatterSourceQuery);
  1921. }
  1922. /**
  1923. * Tests that when using `beforeFind` events, results formatters for
  1924. * queries of non-joined associations do receive the association target
  1925. * query, not the source query.
  1926. */
  1927. public function testResultFormatterReceivesTheTargetQueryForNonJoinedAssociationsWhenUsingBeforeFind(): void
  1928. {
  1929. $articles = $this->getTableLocator()->get('Articles');
  1930. $tags = $articles->belongsToMany('Tags');
  1931. $resultFormatterTargetQuery = null;
  1932. $resultFormatterSourceQuery = null;
  1933. $tags->getEventManager()->on(
  1934. 'Model.beforeFind',
  1935. function ($event, Query $targetQuery) use (&$resultFormatterTargetQuery, &$resultFormatterSourceQuery): void {
  1936. $resultFormatterTargetQuery = $targetQuery;
  1937. $targetQuery->formatResults(function ($results, $query) use (&$resultFormatterSourceQuery) {
  1938. $resultFormatterSourceQuery = $query;
  1939. return $results;
  1940. });
  1941. }
  1942. );
  1943. $sourceQuery = $articles
  1944. ->find('all')
  1945. ->contain('Tags');
  1946. $sourceQuery->firstOrFail();
  1947. $this->assertNotSame($sourceQuery, $resultFormatterTargetQuery);
  1948. $this->assertNotSame($sourceQuery, $resultFormatterSourceQuery);
  1949. $this->assertSame($resultFormatterTargetQuery, $resultFormatterSourceQuery);
  1950. }
  1951. /**
  1952. * Tests that when using `contain()` callables, results formatters for
  1953. * queries of non-joined associations do receive the association target
  1954. * query, not the source query.
  1955. */
  1956. public function testResultFormatterReceivesTheTargetQueryForNonJoinedAssociationsWhenUsingContainCallables(): void
  1957. {
  1958. $articles = $this->getTableLocator()->get('Articles');
  1959. $articles->belongsToMany('Tags');
  1960. $resultFormatterTargetQuery = null;
  1961. $resultFormatterSourceQuery = null;
  1962. $sourceQuery = $articles
  1963. ->find()
  1964. ->contain('Tags', function (Query $targetQuery) use (
  1965. &$resultFormatterTargetQuery,
  1966. &$resultFormatterSourceQuery
  1967. ) {
  1968. $resultFormatterTargetQuery = $targetQuery;
  1969. return $targetQuery->formatResults(function ($results, $query) use (&$resultFormatterSourceQuery) {
  1970. $resultFormatterSourceQuery = $query;
  1971. return $results;
  1972. });
  1973. });
  1974. $sourceQuery->firstOrFail();
  1975. $this->assertNotSame($sourceQuery, $resultFormatterTargetQuery);
  1976. $this->assertNotSame($sourceQuery, $resultFormatterSourceQuery);
  1977. $this->assertSame($resultFormatterTargetQuery, $resultFormatterSourceQuery);
  1978. }
  1979. /**
  1980. * Test fetching results from a qurey with a custom formatter
  1981. */
  1982. public function testQueryWithFormatter(): void
  1983. {
  1984. $table = $this->getTableLocator()->get('authors');
  1985. $query = new Query($this->connection, $table);
  1986. $query->select()->formatResults(function ($results) {
  1987. $this->assertInstanceOf('Cake\ORM\ResultSet', $results);
  1988. return $results->indexBy('id');
  1989. });
  1990. $this->assertEquals([1, 2, 3, 4], array_keys($query->toArray()));
  1991. }
  1992. /**
  1993. * Test fetching results from a qurey with a two custom formatters
  1994. */
  1995. public function testQueryWithStackedFormatters(): void
  1996. {
  1997. $table = $this->getTableLocator()->get('authors');
  1998. $query = new Query($this->connection, $table);
  1999. $query->select()->formatResults(function ($results) {
  2000. $this->assertInstanceOf('Cake\ORM\ResultSet', $results);
  2001. return $results->indexBy('id');
  2002. });
  2003. $query->formatResults(function ($results) {
  2004. return $results->extract('name');
  2005. });
  2006. $expected = [
  2007. 1 => 'mariano',
  2008. 2 => 'nate',
  2009. 3 => 'larry',
  2010. 4 => 'garrett',
  2011. ];
  2012. $this->assertEquals($expected, $query->toArray());
  2013. }
  2014. /**
  2015. * Tests that getting results from a query having a contained association
  2016. * will not attach joins twice if count() is called on it afterwards
  2017. */
  2018. public function testCountWithContainCallingAll(): void
  2019. {
  2020. $table = $this->getTableLocator()->get('articles');
  2021. $table->belongsTo('authors');
  2022. $query = $table->find()
  2023. ->select(['id', 'title'])
  2024. ->contain('authors')
  2025. ->limit(2);
  2026. $results = $query->all();
  2027. $this->assertCount(2, $results);
  2028. $this->assertEquals(3, $query->count());
  2029. }
  2030. /**
  2031. * Verify that only one count query is issued
  2032. * A subsequent request for the count will take the previously
  2033. * returned value
  2034. */
  2035. public function testCountCache(): void
  2036. {
  2037. $query = $this->getMockBuilder('Cake\ORM\Query')
  2038. ->disableOriginalConstructor()
  2039. ->onlyMethods(['_performCount'])
  2040. ->getMock();
  2041. $query->expects($this->once())
  2042. ->method('_performCount')
  2043. ->will($this->returnValue(1));
  2044. $result = $query->count();
  2045. $this->assertSame(1, $result, 'The result of the sql query should be returned');
  2046. $resultAgain = $query->count();
  2047. $this->assertSame(1, $resultAgain, 'No query should be issued and the cached value returned');
  2048. }
  2049. /**
  2050. * If the query is dirty the cached value should be ignored
  2051. * and a new count query issued
  2052. */
  2053. public function testCountCacheDirty(): void
  2054. {
  2055. $query = $this->getMockBuilder('Cake\ORM\Query')
  2056. ->disableOriginalConstructor()
  2057. ->onlyMethods(['_performCount'])
  2058. ->getMock();
  2059. $query->expects($this->exactly(2))
  2060. ->method('_performCount')
  2061. ->will($this->onConsecutiveCalls(1, 2));
  2062. $result = $query->count();
  2063. $this->assertSame(1, $result, 'The result of the sql query should be returned');
  2064. $query->where(['dirty' => 'cache']);
  2065. $secondResult = $query->count();
  2066. $this->assertSame(2, $secondResult, 'The query cache should be dropped with any modification');
  2067. $thirdResult = $query->count();
  2068. $this->assertSame(2, $thirdResult, 'The query has not been modified, the cached value is valid');
  2069. }
  2070. /**
  2071. * Tests that it is possible to apply formatters inside the query builder
  2072. * for belongsTo associations
  2073. */
  2074. public function testFormatBelongsToRecords(): void
  2075. {
  2076. $table = $this->getTableLocator()->get('articles');
  2077. $table->belongsTo('authors');
  2078. $query = $table->find()
  2079. ->contain([
  2080. 'authors' => function ($q) {
  2081. return $q
  2082. ->formatResults(function ($authors) {
  2083. return $authors->map(function ($author) {
  2084. $author->idCopy = $author->id;
  2085. return $author;
  2086. });
  2087. })
  2088. ->formatResults(function ($authors) {
  2089. return $authors->map(function ($author) {
  2090. $author->idCopy = $author->idCopy + 2;
  2091. return $author;
  2092. });
  2093. });
  2094. },
  2095. ]);
  2096. $query->formatResults(function ($results) {
  2097. return $results->combine('id', 'author.idCopy');
  2098. });
  2099. $results = $query->toArray();
  2100. $expected = [1 => 3, 2 => 5, 3 => 3];
  2101. $this->assertEquals($expected, $results);
  2102. }
  2103. /**
  2104. * Tests it is possible to apply formatters to deep relations.
  2105. */
  2106. public function testFormatDeepAssociationRecords(): void
  2107. {
  2108. $table = $this->getTableLocator()->get('ArticlesTags');
  2109. $table->belongsTo('Articles');
  2110. $table->getAssociation('Articles')->getTarget()->belongsTo('Authors');
  2111. $builder = function ($q) {
  2112. return $q
  2113. ->formatResults(function ($results) {
  2114. return $results->map(function ($result) {
  2115. $result->idCopy = $result->id;
  2116. return $result;
  2117. });
  2118. })
  2119. ->formatResults(function ($results) {
  2120. return $results->map(function ($result) {
  2121. $result->idCopy = $result->idCopy + 2;
  2122. return $result;
  2123. });
  2124. });
  2125. };
  2126. $query = $table->find()
  2127. ->contain(['Articles' => $builder, 'Articles.Authors' => $builder])
  2128. ->order(['ArticlesTags.article_id' => 'ASC']);
  2129. $query->formatResults(function ($results) {
  2130. return $results->map(function ($row) {
  2131. return sprintf(
  2132. '%s - %s - %s',
  2133. $row->tag_id,
  2134. $row->article->idCopy,
  2135. $row->article->author->idCopy
  2136. );
  2137. });
  2138. });
  2139. $expected = ['1 - 3 - 3', '2 - 3 - 3', '1 - 4 - 5', '3 - 4 - 5'];
  2140. $this->assertEquals($expected, $query->toArray());
  2141. }
  2142. /**
  2143. * Tests that formatters cna be applied to deep associations that are fetched using
  2144. * additional queries
  2145. */
  2146. public function testFormatDeepDistantAssociationRecords(): void
  2147. {
  2148. $table = $this->getTableLocator()->get('authors');
  2149. $table->hasMany('articles');
  2150. $articles = $table->getAssociation('articles')->getTarget();
  2151. $articles->hasMany('articlesTags');
  2152. $articles->getAssociation('articlesTags')->getTarget()->belongsTo('tags');
  2153. $query = $table->find()->contain([
  2154. 'articles.articlesTags.tags' => function ($q) {
  2155. return $q->formatResults(function ($results) {
  2156. return $results->map(function ($tag) {
  2157. $tag->name .= ' - visited';
  2158. return $tag;
  2159. });
  2160. });
  2161. },
  2162. ]);
  2163. $query->mapReduce(function ($row, $key, $mr): void {
  2164. foreach ((array)$row->articles as $article) {
  2165. foreach ((array)$article->articles_tags as $articleTag) {
  2166. $mr->emit($articleTag->tag->name);
  2167. }
  2168. }
  2169. });
  2170. $expected = ['tag1 - visited', 'tag2 - visited', 'tag1 - visited', 'tag3 - visited'];
  2171. $this->assertEquals($expected, $query->toArray());
  2172. }
  2173. /**
  2174. * Tests that custom finders are applied to associations when using the proxies
  2175. */
  2176. public function testCustomFinderInBelongsTo(): void
  2177. {
  2178. $table = $this->getTableLocator()->get('ArticlesTags');
  2179. $table->belongsTo('Articles', [
  2180. 'className' => 'TestApp\Model\Table\ArticlesTable',
  2181. 'finder' => 'published',
  2182. ]);
  2183. $result = $table->find()->contain('Articles');
  2184. $this->assertCount(4, $result->all()->extract('article')->filter()->toArray());
  2185. $table->Articles->updateAll(['published' => 'N'], ['1 = 1']);
  2186. $result = $table->find()->contain('Articles');
  2187. $this->assertCount(0, $result->all()->extract('article')->filter()->toArray());
  2188. }
  2189. /**
  2190. * Test finding fields on the non-default table that
  2191. * have the same name as the primary table.
  2192. */
  2193. public function testContainSelectedFields(): void
  2194. {
  2195. $table = $this->getTableLocator()->get('Articles');
  2196. $table->belongsTo('Authors');
  2197. $query = $table->find()
  2198. ->contain(['Authors'])
  2199. ->order(['Authors.id' => 'asc'])
  2200. ->select(['Authors.id']);
  2201. $results = $query->all()->extract('author.id')->toList();
  2202. $expected = [1, 1, 3];
  2203. $this->assertEquals($expected, $results);
  2204. }
  2205. /**
  2206. * Tests that it is possible to attach more association when using a query
  2207. * builder for other associations
  2208. */
  2209. public function testContainInAssociationQuery(): void
  2210. {
  2211. $table = $this->getTableLocator()->get('ArticlesTags');
  2212. $table->belongsTo('Articles');
  2213. $table->getAssociation('Articles')->getTarget()->belongsTo('Authors');
  2214. $query = $table->find()
  2215. ->order(['Articles.id' => 'ASC'])
  2216. ->contain([
  2217. 'Articles' => function ($q) {
  2218. return $q->contain('Authors');
  2219. },
  2220. ]);
  2221. $results = $query->all()->extract('article.author.name')->toArray();
  2222. $expected = ['mariano', 'mariano', 'larry', 'larry'];
  2223. $this->assertEquals($expected, $results);
  2224. }
  2225. /**
  2226. * Tests that it is possible to apply more `matching` conditions inside query
  2227. * builders for associations
  2228. */
  2229. public function testContainInAssociationMatching(): void
  2230. {
  2231. $table = $this->getTableLocator()->get('authors');
  2232. $table->hasMany('articles');
  2233. $articles = $table->getAssociation('articles')->getTarget();
  2234. $articles->hasMany('articlesTags');
  2235. $articles->getAssociation('articlesTags')->getTarget()->belongsTo('tags');
  2236. $query = $table->find()->matching('articles.articlesTags', function ($q) {
  2237. return $q->matching('tags', function ($q) {
  2238. return $q->where(['tags.name' => 'tag3']);
  2239. });
  2240. });
  2241. $results = $query->toArray();
  2242. $this->assertCount(1, $results);
  2243. $this->assertSame('tag3', $results[0]->_matchingData['tags']->name);
  2244. }
  2245. /**
  2246. * Tests __debugInfo
  2247. */
  2248. public function testDebugInfo(): void
  2249. {
  2250. $table = $this->getTableLocator()->get('authors');
  2251. $table->hasMany('articles');
  2252. $query = $table->find()
  2253. ->where(['id > ' => 1])
  2254. ->enableHydration(false)
  2255. ->matching('articles')
  2256. ->applyOptions(['foo' => 'bar'])
  2257. ->formatResults(function ($results) {
  2258. return $results;
  2259. })
  2260. ->mapReduce(function ($item, $key, $mr): void {
  2261. $mr->emit($item);
  2262. });
  2263. $expected = [
  2264. '(help)' => 'This is a Query object, to get the results execute or iterate it.',
  2265. 'sql' => $query->sql(),
  2266. 'params' => $query->getValueBinder()->bindings(),
  2267. 'defaultTypes' => [
  2268. 'authors__id' => 'integer',
  2269. 'authors.id' => 'integer',
  2270. 'id' => 'integer',
  2271. 'authors__name' => 'string',
  2272. 'authors.name' => 'string',
  2273. 'name' => 'string',
  2274. 'articles__id' => 'integer',
  2275. 'articles.id' => 'integer',
  2276. 'articles__author_id' => 'integer',
  2277. 'articles.author_id' => 'integer',
  2278. 'author_id' => 'integer',
  2279. 'articles__title' => 'string',
  2280. 'articles.title' => 'string',
  2281. 'title' => 'string',
  2282. 'articles__body' => 'text',
  2283. 'articles.body' => 'text',
  2284. 'body' => 'text',
  2285. 'articles__published' => 'string',
  2286. 'articles.published' => 'string',
  2287. 'published' => 'string',
  2288. ],
  2289. 'executed' => false,
  2290. 'decorators' => 0,
  2291. 'hydrate' => false,
  2292. 'formatters' => 1,
  2293. 'mapReducers' => 1,
  2294. 'contain' => [],
  2295. 'matching' => [
  2296. 'articles' => [
  2297. 'matching' => true,
  2298. 'queryBuilder' => null,
  2299. 'joinType' => 'INNER',
  2300. ],
  2301. ],
  2302. 'extraOptions' => ['foo' => 'bar'],
  2303. 'repository' => $table,
  2304. ];
  2305. $this->assertSame($expected, $query->__debugInfo());
  2306. }
  2307. /**
  2308. * Tests that the eagerLoaded function works and is transmitted correctly to eagerly
  2309. * loaded associations
  2310. */
  2311. public function testEagerLoaded(): void
  2312. {
  2313. $table = $this->getTableLocator()->get('authors');
  2314. $table->hasMany('articles');
  2315. $query = $table->find()->contain([
  2316. 'articles' => function ($q) {
  2317. $this->assertTrue($q->isEagerLoaded());
  2318. return $q;
  2319. },
  2320. ]);
  2321. $this->assertFalse($query->isEagerLoaded());
  2322. $table->getEventManager()->on('Model.beforeFind', function ($e, $q, $o, $primary): void {
  2323. $this->assertTrue($primary);
  2324. });
  2325. $this->getTableLocator()->get('articles')
  2326. ->getEventManager()->on('Model.beforeFind', function ($e, $q, $o, $primary): void {
  2327. $this->assertFalse($primary);
  2328. });
  2329. $query->all();
  2330. }
  2331. /**
  2332. * Tests that the isEagerLoaded function works and is transmitted correctly to eagerly
  2333. * loaded associations
  2334. */
  2335. public function testIsEagerLoaded(): void
  2336. {
  2337. $table = $this->getTableLocator()->get('authors');
  2338. $table->hasMany('articles');
  2339. $query = $table->find()->contain([
  2340. 'articles' => function ($q) {
  2341. $this->assertTrue($q->isEagerLoaded());
  2342. return $q;
  2343. },
  2344. ]);
  2345. $this->assertFalse($query->isEagerLoaded());
  2346. $table->getEventManager()->on('Model.beforeFind', function ($e, $q, $o, $primary): void {
  2347. $this->assertTrue($primary);
  2348. });
  2349. $this->getTableLocator()->get('articles')
  2350. ->getEventManager()->on('Model.beforeFind', function ($e, $q, $o, $primary): void {
  2351. $this->assertFalse($primary);
  2352. });
  2353. $query->all();
  2354. }
  2355. /**
  2356. * Tests that columns from manual joins are also contained in the result set
  2357. */
  2358. public function testColumnsFromJoin(): void
  2359. {
  2360. $table = $this->getTableLocator()->get('articles');
  2361. $query = $table->find();
  2362. $results = $query
  2363. ->select(['title', 'person.name'])
  2364. ->join([
  2365. 'person' => [
  2366. 'table' => 'authors',
  2367. 'conditions' => [$query->newExpr()->equalFields('person.id', 'articles.author_id')],
  2368. ],
  2369. ])
  2370. ->order(['articles.id' => 'ASC'])
  2371. ->enableHydration(false)
  2372. ->toArray();
  2373. $expected = [
  2374. ['title' => 'First Article', 'person' => ['name' => 'mariano']],
  2375. ['title' => 'Second Article', 'person' => ['name' => 'larry']],
  2376. ['title' => 'Third Article', 'person' => ['name' => 'mariano']],
  2377. ];
  2378. $this->assertSame($expected, $results);
  2379. }
  2380. /**
  2381. * Tests that it is possible to use the same association aliases in the association
  2382. * chain for contain
  2383. *
  2384. * @dataProvider strategiesProviderBelongsTo
  2385. */
  2386. public function testRepeatedAssociationAliases(string $strategy): void
  2387. {
  2388. $table = $this->getTableLocator()->get('ArticlesTags');
  2389. $table->belongsTo('Articles', ['strategy' => $strategy]);
  2390. $table->belongsTo('Tags', ['strategy' => $strategy]);
  2391. $this->getTableLocator()->get('Tags')->belongsToMany('Articles');
  2392. $results = $table
  2393. ->find()
  2394. ->contain(['Articles', 'Tags.Articles'])
  2395. ->enableHydration(false)
  2396. ->toArray();
  2397. $this->assertNotEmpty($results[0]['tag']['articles']);
  2398. $this->assertNotEmpty($results[0]['article']);
  2399. $this->assertNotEmpty($results[1]['tag']['articles']);
  2400. $this->assertNotEmpty($results[1]['article']);
  2401. $this->assertNotEmpty($results[2]['tag']['articles']);
  2402. $this->assertNotEmpty($results[2]['article']);
  2403. }
  2404. /**
  2405. * Tests that a hasOne association using the select strategy will still have the
  2406. * key present in the results when no match is found
  2407. */
  2408. public function testAssociationKeyPresent(): void
  2409. {
  2410. $table = $this->getTableLocator()->get('Articles');
  2411. $table->hasOne('ArticlesTags', ['strategy' => 'select']);
  2412. $article = $table->find()->where(['id' => 3])
  2413. ->enableHydration(false)
  2414. ->contain('ArticlesTags')
  2415. ->first();
  2416. $this->assertNull($article['articles_tag']);
  2417. }
  2418. /**
  2419. * Tests that queries can be serialized to JSON to get the results
  2420. */
  2421. public function testJsonSerialize(): void
  2422. {
  2423. $table = $this->getTableLocator()->get('Articles');
  2424. $this->assertEquals(
  2425. json_encode($table->find()),
  2426. json_encode($table->find()->toArray())
  2427. );
  2428. }
  2429. /**
  2430. * Test that addFields() works in the basic case.
  2431. */
  2432. public function testAutoFields(): void
  2433. {
  2434. $table = $this->getTableLocator()->get('Articles');
  2435. $result = $table->find('all')
  2436. ->select(['myField' => '(SELECT 20)'])
  2437. ->enableAutoFields()
  2438. ->enableHydration(false)
  2439. ->first();
  2440. $this->assertArrayHasKey('myField', $result);
  2441. $this->assertArrayHasKey('id', $result);
  2442. $this->assertArrayHasKey('title', $result);
  2443. }
  2444. /**
  2445. * Test autoFields with auto fields.
  2446. */
  2447. public function testAutoFieldsWithAssociations(): void
  2448. {
  2449. $table = $this->getTableLocator()->get('Articles');
  2450. $table->belongsTo('Authors');
  2451. $result = $table->find()
  2452. ->select(['myField' => '(SELECT 2 + 2)'])
  2453. ->enableAutoFields()
  2454. ->enableHydration(false)
  2455. ->contain('Authors')
  2456. ->first();
  2457. $this->assertArrayHasKey('myField', $result);
  2458. $this->assertArrayHasKey('title', $result);
  2459. $this->assertArrayHasKey('author', $result);
  2460. $this->assertNotNull($result['author']);
  2461. $this->assertArrayHasKey('name', $result['author']);
  2462. }
  2463. /**
  2464. * Test autoFields in contain query builder
  2465. */
  2466. public function testAutoFieldsWithContainQueryBuilder(): void
  2467. {
  2468. $table = $this->getTableLocator()->get('Articles');
  2469. $table->belongsTo('Authors');
  2470. $result = $table->find()
  2471. ->select(['myField' => '(SELECT 2 + 2)'])
  2472. ->enableAutoFields()
  2473. ->enableHydration(false)
  2474. ->contain([
  2475. 'Authors' => function ($q) {
  2476. return $q->select(['computed' => '(SELECT 2 + 20)'])
  2477. ->enableAutoFields();
  2478. },
  2479. ])
  2480. ->first();
  2481. $this->assertArrayHasKey('myField', $result);
  2482. $this->assertArrayHasKey('title', $result);
  2483. $this->assertArrayHasKey('author', $result);
  2484. $this->assertNotNull($result['author']);
  2485. $this->assertArrayHasKey('name', $result['author']);
  2486. $this->assertArrayHasKey('computed', $result);
  2487. }
  2488. /**
  2489. * Test that autofields works with count()
  2490. */
  2491. public function testAutoFieldsCount(): void
  2492. {
  2493. $table = $this->getTableLocator()->get('Articles');
  2494. $result = $table->find()
  2495. ->select(['myField' => '(SELECT (2 + 2))'])
  2496. ->enableAutoFields()
  2497. ->count();
  2498. $this->assertEquals(3, $result);
  2499. }
  2500. /**
  2501. * test that cleanCopy makes a cleaned up clone.
  2502. */
  2503. public function testCleanCopy(): void
  2504. {
  2505. $table = $this->getTableLocator()->get('Articles');
  2506. $table->hasMany('Comments');
  2507. $query = $table->find();
  2508. $query->offset(10)
  2509. ->limit(1)
  2510. ->order(['Articles.id' => 'DESC'])
  2511. ->contain(['Comments'])
  2512. ->matching('Comments');
  2513. $copy = $query->cleanCopy();
  2514. $this->assertNotSame($copy, $query);
  2515. $copyLoader = $copy->getEagerLoader();
  2516. $loader = $query->getEagerLoader();
  2517. $this->assertEquals($copyLoader, $loader, 'should be equal');
  2518. $this->assertNotSame($copyLoader, $loader, 'should be clones');
  2519. $reflect = new ReflectionProperty($loader, '_matching');
  2520. $reflect->setAccessible(true);
  2521. $this->assertNotSame(
  2522. $reflect->getValue($copyLoader),
  2523. $reflect->getValue($loader),
  2524. 'should be clones'
  2525. );
  2526. $this->assertNull($copy->clause('offset'));
  2527. $this->assertNull($copy->clause('limit'));
  2528. $this->assertNull($copy->clause('order'));
  2529. }
  2530. /**
  2531. * test that cleanCopy retains bindings
  2532. */
  2533. public function testCleanCopyRetainsBindings(): void
  2534. {
  2535. $table = $this->getTableLocator()->get('Articles');
  2536. $query = $table->find();
  2537. $query->offset(10)
  2538. ->limit(1)
  2539. ->where(['Articles.id BETWEEN :start AND :end'])
  2540. ->order(['Articles.id' => 'DESC'])
  2541. ->bind(':start', 1)
  2542. ->bind(':end', 2);
  2543. $copy = $query->cleanCopy();
  2544. $this->assertNotEmpty($copy->getValueBinder()->bindings());
  2545. }
  2546. /**
  2547. * test that cleanCopy makes a cleaned up clone with a beforeFind.
  2548. */
  2549. public function testCleanCopyBeforeFind(): void
  2550. {
  2551. $table = $this->getTableLocator()->get('Articles');
  2552. $table->hasMany('Comments');
  2553. $table->getEventManager()
  2554. ->on('Model.beforeFind', function (EventInterface $event, $query): void {
  2555. $query
  2556. ->limit(5)
  2557. ->order(['Articles.title' => 'DESC']);
  2558. });
  2559. $query = $table->find();
  2560. $query->offset(10)
  2561. ->limit(1)
  2562. ->order(['Articles.id' => 'DESC'])
  2563. ->contain(['Comments']);
  2564. $copy = $query->cleanCopy();
  2565. $this->assertNotSame($copy, $query);
  2566. $this->assertNull($copy->clause('offset'));
  2567. $this->assertNull($copy->clause('limit'));
  2568. $this->assertNull($copy->clause('order'));
  2569. }
  2570. /**
  2571. * Test that finder options sent through via contain are sent to custom finder for belongsTo associations.
  2572. */
  2573. public function testContainFinderBelongsTo(): void
  2574. {
  2575. $table = $this->getTableLocator()->get('Articles');
  2576. $table->belongsTo(
  2577. 'Authors',
  2578. ['className' => 'TestApp\Model\Table\AuthorsTable']
  2579. );
  2580. $authorId = 1;
  2581. $resultWithoutAuthor = $table->find('all')
  2582. ->where(['Articles.author_id' => $authorId])
  2583. ->contain([
  2584. 'Authors' => [
  2585. 'finder' => ['byAuthor' => ['author_id' => 2]],
  2586. ],
  2587. ]);
  2588. $resultWithAuthor = $table->find('all')
  2589. ->where(['Articles.author_id' => $authorId])
  2590. ->contain([
  2591. 'Authors' => [
  2592. 'finder' => ['byAuthor' => ['author_id' => $authorId]],
  2593. ],
  2594. ]);
  2595. $this->assertEmpty($resultWithoutAuthor->first()['author']);
  2596. $this->assertEquals($authorId, $resultWithAuthor->first()['author']['id']);
  2597. }
  2598. /**
  2599. * Test that finder options sent through via contain are sent to custom finder for hasMany associations.
  2600. */
  2601. public function testContainFinderHasMany(): void
  2602. {
  2603. $table = $this->getTableLocator()->get('Authors');
  2604. $table->hasMany(
  2605. 'Articles',
  2606. ['className' => 'TestApp\Model\Table\ArticlesTable']
  2607. );
  2608. $newArticle = $table->newEntity([
  2609. 'author_id' => 1,
  2610. 'title' => 'Fourth Article',
  2611. 'body' => 'Fourth Article Body',
  2612. 'published' => 'N',
  2613. ]);
  2614. $table->save($newArticle);
  2615. $resultWithArticles = $table->find('all')
  2616. ->where(['id' => 1])
  2617. ->contain([
  2618. 'Articles' => [
  2619. 'finder' => 'published',
  2620. ],
  2621. ]);
  2622. $resultWithArticlesArray = $table->find('all')
  2623. ->where(['id' => 1])
  2624. ->contain([
  2625. 'Articles' => [
  2626. 'finder' => ['published' => []],
  2627. ],
  2628. ]);
  2629. $resultWithArticlesArrayOptions = $table->find('all')
  2630. ->where(['id' => 1])
  2631. ->contain([
  2632. 'Articles' => [
  2633. 'finder' => [
  2634. 'published' => [
  2635. 'title' => 'First Article',
  2636. ],
  2637. ],
  2638. ],
  2639. ]);
  2640. $resultWithoutArticles = $table->find('all')
  2641. ->where(['id' => 1])
  2642. ->contain([
  2643. 'Articles' => [
  2644. 'finder' => [
  2645. 'published' => [
  2646. 'title' => 'Foo',
  2647. ],
  2648. ],
  2649. ],
  2650. ]);
  2651. $this->assertCount(2, $resultWithArticles->first()->articles);
  2652. $this->assertCount(2, $resultWithArticlesArray->first()->articles);
  2653. $this->assertCount(1, $resultWithArticlesArrayOptions->first()->articles);
  2654. $this->assertSame(
  2655. 'First Article',
  2656. $resultWithArticlesArrayOptions->first()->articles[0]->title
  2657. );
  2658. $this->assertCount(0, $resultWithoutArticles->first()->articles);
  2659. }
  2660. /**
  2661. * Test that using a closure for a custom finder for contain works.
  2662. */
  2663. public function testContainFinderHasManyClosure(): void
  2664. {
  2665. $table = $this->getTableLocator()->get('Authors');
  2666. $table->hasMany(
  2667. 'Articles',
  2668. ['className' => 'TestApp\Model\Table\ArticlesTable']
  2669. );
  2670. $newArticle = $table->newEntity([
  2671. 'author_id' => 1,
  2672. 'title' => 'Fourth Article',
  2673. 'body' => 'Fourth Article Body',
  2674. 'published' => 'N',
  2675. ]);
  2676. $table->save($newArticle);
  2677. $resultWithArticles = $table->find('all')
  2678. ->where(['id' => 1])
  2679. ->contain([
  2680. 'Articles' => function ($q) {
  2681. return $q->find('published');
  2682. },
  2683. ]);
  2684. $this->assertCount(2, $resultWithArticles->first()->articles);
  2685. }
  2686. /**
  2687. * Tests that it is possible to bind arguments to a query and it will return the right
  2688. * results
  2689. */
  2690. public function testCustomBindings(): void
  2691. {
  2692. $table = $this->getTableLocator()->get('Articles');
  2693. $query = $table->find()->where(['id >' => 1]);
  2694. $query->where(function ($exp) {
  2695. return $exp->add('author_id = :author');
  2696. });
  2697. $query->bind(':author', 1, 'integer');
  2698. $this->assertEquals(1, $query->count());
  2699. $this->assertEquals(3, $query->first()->id);
  2700. }
  2701. /**
  2702. * Tests that it is possible to pass a custom join type for an association when
  2703. * using contain
  2704. */
  2705. public function testContainWithCustomJoinType(): void
  2706. {
  2707. $table = $this->getTableLocator()->get('Articles');
  2708. $table->belongsTo('Authors');
  2709. $articles = $table->find()
  2710. ->contain([
  2711. 'Authors' => [
  2712. 'joinType' => 'inner',
  2713. 'conditions' => ['Authors.id' => 3],
  2714. ],
  2715. ])
  2716. ->toArray();
  2717. $this->assertCount(1, $articles);
  2718. $this->assertEquals(3, $articles[0]->author->id);
  2719. }
  2720. /**
  2721. * Tests that it is possible to override the contain strategy using the
  2722. * containments array. In this case, no inner join will be made and for that
  2723. * reason, the parent association will not be filtered as the strategy changed
  2724. * from join to select.
  2725. */
  2726. public function testContainWithStrategyOverride(): void
  2727. {
  2728. $table = $this->getTableLocator()->get('Articles');
  2729. $table->belongsTo('Authors', [
  2730. 'joinType' => 'INNER',
  2731. ]);
  2732. $articles = $table->find()
  2733. ->contain([
  2734. 'Authors' => [
  2735. 'strategy' => 'select',
  2736. 'conditions' => ['Authors.id' => 3],
  2737. ],
  2738. ])
  2739. ->toArray();
  2740. $this->assertCount(3, $articles);
  2741. $this->assertEquals(3, $articles[1]->author->id);
  2742. $this->assertNull($articles[0]->author);
  2743. $this->assertNull($articles[2]->author);
  2744. }
  2745. /**
  2746. * Tests that it is possible to call matching and contain on the same
  2747. * association.
  2748. */
  2749. public function testMatchingWithContain(): void
  2750. {
  2751. $query = new Query($this->connection, $this->table);
  2752. $table = $this->getTableLocator()->get('authors');
  2753. $table->hasMany('articles');
  2754. $this->getTableLocator()->get('articles')->belongsToMany('tags');
  2755. $result = $query->setRepository($table)
  2756. ->select()
  2757. ->matching('articles.tags', function ($q) {
  2758. return $q->where(['tags.id' => 2]);
  2759. })
  2760. ->contain('articles')
  2761. ->first();
  2762. $this->assertEquals(1, $result->id);
  2763. $this->assertCount(2, $result->articles);
  2764. $this->assertEquals(2, $result->_matchingData['tags']->id);
  2765. }
  2766. /**
  2767. * Tests that it is possible to call matching and contain on the same
  2768. * association with only one level of depth.
  2769. */
  2770. public function testNotSoFarMatchingWithContainOnTheSameAssociation(): void
  2771. {
  2772. $table = $this->getTableLocator()->get('articles');
  2773. $table->belongsToMany('tags');
  2774. $result = $table->find()
  2775. ->matching('tags', function ($q) {
  2776. return $q->where(['tags.id' => 2]);
  2777. })
  2778. ->contain('tags')
  2779. ->first();
  2780. $this->assertEquals(1, $result->id);
  2781. $this->assertCount(2, $result->tags);
  2782. $this->assertEquals(2, $result->_matchingData['tags']->id);
  2783. }
  2784. /**
  2785. * Tests that it is possible to find large numeric values.
  2786. */
  2787. public function testSelectLargeNumbers(): void
  2788. {
  2789. // Sqlite only supports maximum 16 digits for decimals.
  2790. $this->skipIf($this->connection->getDriver() instanceof Sqlite);
  2791. $big = '1234567890123456789.2';
  2792. $table = $this->getTableLocator()->get('Datatypes');
  2793. $entity = $table->newEntity([]);
  2794. $entity->cost = $big;
  2795. $entity->tiny = 1;
  2796. $entity->small = 10;
  2797. $table->save($entity);
  2798. $out = $table->find()
  2799. ->where([
  2800. 'cost' => $big,
  2801. ])
  2802. ->first();
  2803. $this->assertNotEmpty($out, 'Should get a record');
  2804. $this->assertSame($big, $out->cost);
  2805. $small = '0.1234567890123456789';
  2806. $entity = $table->newEntity(['fraction' => $small]);
  2807. $table->save($entity);
  2808. $out = $table->find()
  2809. ->where([
  2810. 'fraction' => $small,
  2811. ])
  2812. ->first();
  2813. $this->assertNotEmpty($out, 'Should get a record');
  2814. $this->assertMatchesRegularExpression('/^0?\.1234567890123456789$/', $out->fraction);
  2815. $small = 0.1234567890123456789;
  2816. $entity = $table->newEntity(['fraction' => $small]);
  2817. $table->save($entity);
  2818. $out = $table->find()
  2819. ->where([
  2820. 'fraction' => $small,
  2821. ])
  2822. ->first();
  2823. $this->assertNotEmpty($out, 'Should get a record');
  2824. // There will be loss of precision if too large/small value is set as float instead of string.
  2825. $this->assertMatchesRegularExpression('/^0?\.123456789012350+$/', $out->fraction);
  2826. }
  2827. /**
  2828. * Tests that select() can be called with Table and Association
  2829. * instance
  2830. */
  2831. public function testSelectWithTableAndAssociationInstance(): void
  2832. {
  2833. $table = $this->getTableLocator()->get('articles');
  2834. $table->belongsTo('authors');
  2835. $result = $table
  2836. ->find()
  2837. ->select(function ($q) {
  2838. return ['foo' => $q->newExpr('1 + 1')];
  2839. })
  2840. ->select($table)
  2841. ->select($table->authors)
  2842. ->contain(['authors'])
  2843. ->first();
  2844. $expected = $table
  2845. ->find()
  2846. ->select(function ($q) {
  2847. return ['foo' => $q->newExpr('1 + 1')];
  2848. })
  2849. ->enableAutoFields()
  2850. ->contain(['authors'])
  2851. ->first();
  2852. $this->assertNotEmpty($result);
  2853. $this->assertEquals($expected, $result);
  2854. }
  2855. /**
  2856. * Test that simple aliased field have results typecast.
  2857. */
  2858. public function testSelectTypeInferSimpleAliases(): void
  2859. {
  2860. $table = $this->getTableLocator()->get('comments');
  2861. $result = $table
  2862. ->find()
  2863. ->select(['created', 'updated_time' => 'updated'])
  2864. ->first();
  2865. $this->assertInstanceOf(DateTime::class, $result->created);
  2866. $this->assertInstanceOf(DateTime::class, $result->updated_time);
  2867. }
  2868. /**
  2869. * Tests that leftJoinWith() creates a left join with a given association and
  2870. * that no fields from such association are loaded.
  2871. */
  2872. public function testLeftJoinWith(): void
  2873. {
  2874. $table = $this->getTableLocator()->get('authors');
  2875. $table->hasMany('articles');
  2876. $table->articles->deleteAll(['author_id' => 4]);
  2877. $results = $table
  2878. ->find()
  2879. ->select(['total_articles' => 'count(articles.id)'])
  2880. ->enableAutoFields()
  2881. ->leftJoinWith('articles')
  2882. ->group(['authors.id', 'authors.name']);
  2883. $expected = [
  2884. 1 => 2,
  2885. 2 => 0,
  2886. 3 => 1,
  2887. 4 => 0,
  2888. ];
  2889. $this->assertEquals($expected, $results->all()->combine('id', 'total_articles')->toArray());
  2890. $fields = ['total_articles', 'id', 'name'];
  2891. $this->assertEquals($fields, array_keys($results->first()->toArray()));
  2892. $results = $table
  2893. ->find()
  2894. ->leftJoinWith('articles')
  2895. ->where(['articles.id IS' => null]);
  2896. $this->assertEquals([2, 4], $results->all()->extract('id')->toList());
  2897. $this->assertEquals(['id', 'name'], array_keys($results->first()->toArray()));
  2898. $results = $table
  2899. ->find()
  2900. ->leftJoinWith('articles')
  2901. ->where(['articles.id IS NOT' => null])
  2902. ->order(['authors.id']);
  2903. $this->assertEquals([1, 1, 3], $results->all()->extract('id')->toList());
  2904. $this->assertEquals(['id', 'name'], array_keys($results->first()->toArray()));
  2905. }
  2906. /**
  2907. * Tests that leftJoinWith() creates a left join with a given association and
  2908. * that no fields from such association are loaded.
  2909. */
  2910. public function testLeftJoinWithNested(): void
  2911. {
  2912. $table = $this->getTableLocator()->get('authors');
  2913. $articles = $table->hasMany('articles');
  2914. $articles->belongsToMany('tags');
  2915. $results = $table
  2916. ->find()
  2917. ->select([
  2918. 'authors.id',
  2919. 'tagged_articles' => 'count(tags.id)',
  2920. ])
  2921. ->leftJoinWith('articles.tags', function ($q) {
  2922. return $q->where(['tags.name' => 'tag3']);
  2923. })
  2924. ->group(['authors.id']);
  2925. $expected = [
  2926. 1 => 0,
  2927. 2 => 0,
  2928. 3 => 1,
  2929. 4 => 0,
  2930. ];
  2931. $this->assertEquals($expected, $results->all()->combine('id', 'tagged_articles')->toArray());
  2932. }
  2933. /**
  2934. * Tests that leftJoinWith() can be used with select()
  2935. */
  2936. public function testLeftJoinWithSelect(): void
  2937. {
  2938. $table = $this->getTableLocator()->get('authors');
  2939. $articles = $table->hasMany('articles');
  2940. $articles->belongsToMany('tags');
  2941. $results = $table
  2942. ->find()
  2943. ->leftJoinWith('articles.tags', function ($q) {
  2944. return $q
  2945. ->select(['articles.id', 'articles.title', 'tags.name'])
  2946. ->where(['tags.name' => 'tag3']);
  2947. })
  2948. ->enableAutoFields()
  2949. ->where(['ArticlesTags.tag_id' => 3])
  2950. ->all();
  2951. $expected = ['id' => 2, 'title' => 'Second Article'];
  2952. $this->assertEquals(
  2953. $expected,
  2954. $results->first()->_matchingData['articles']->toArray()
  2955. );
  2956. $this->assertEquals(
  2957. ['name' => 'tag3'],
  2958. $results->first()->_matchingData['tags']->toArray()
  2959. );
  2960. }
  2961. /**
  2962. * Tests that leftJoinWith() can be used with autofields()
  2963. */
  2964. public function testLeftJoinWithAutoFields(): void
  2965. {
  2966. $table = $this->getTableLocator()->get('articles');
  2967. $table->belongsTo('authors');
  2968. $results = $table
  2969. ->find()
  2970. ->leftJoinWith('authors', function ($q) {
  2971. return $q->enableAutoFields();
  2972. })
  2973. ->all();
  2974. $this->assertCount(3, $results);
  2975. }
  2976. /**
  2977. * Test leftJoinWith and contain on optional association
  2978. */
  2979. public function testLeftJoinWithAndContainOnOptionalAssociation(): void
  2980. {
  2981. $table = $this->getTableLocator()->get('Articles', ['table' => 'articles']);
  2982. $table->belongsTo('Authors');
  2983. $newArticle = $table->newEntity([
  2984. 'title' => 'Fourth Article',
  2985. 'body' => 'Fourth Article Body',
  2986. 'published' => 'N',
  2987. ]);
  2988. $table->save($newArticle);
  2989. $results = $table
  2990. ->find()
  2991. ->disableHydration()
  2992. ->contain('Authors')
  2993. ->leftJoinWith('Authors')
  2994. ->all();
  2995. $expected = [
  2996. [
  2997. 'id' => 1,
  2998. 'author_id' => 1,
  2999. 'title' => 'First Article',
  3000. 'body' => 'First Article Body',
  3001. 'published' => 'Y',
  3002. 'author' => [
  3003. 'id' => 1,
  3004. 'name' => 'mariano',
  3005. ],
  3006. ],
  3007. [
  3008. 'id' => 2,
  3009. 'author_id' => 3,
  3010. 'title' => 'Second Article',
  3011. 'body' => 'Second Article Body',
  3012. 'published' => 'Y',
  3013. 'author' => [
  3014. 'id' => 3,
  3015. 'name' => 'larry',
  3016. ],
  3017. ],
  3018. [
  3019. 'id' => 3,
  3020. 'author_id' => 1,
  3021. 'title' => 'Third Article',
  3022. 'body' => 'Third Article Body',
  3023. 'published' => 'Y',
  3024. 'author' => [
  3025. 'id' => 1,
  3026. 'name' => 'mariano',
  3027. ],
  3028. ],
  3029. [
  3030. 'id' => 4,
  3031. 'author_id' => null,
  3032. 'title' => 'Fourth Article',
  3033. 'body' => 'Fourth Article Body',
  3034. 'published' => 'N',
  3035. 'author' => null,
  3036. ],
  3037. ];
  3038. $this->assertEquals($expected, $results->toList());
  3039. $results = $table
  3040. ->find()
  3041. ->disableHydration()
  3042. ->contain('Authors')
  3043. ->leftJoinWith('Authors')
  3044. ->where(['Articles.author_id is' => null])
  3045. ->all();
  3046. $expected = [
  3047. [
  3048. 'id' => 4,
  3049. 'author_id' => null,
  3050. 'title' => 'Fourth Article',
  3051. 'body' => 'Fourth Article Body',
  3052. 'published' => 'N',
  3053. 'author' => null,
  3054. ],
  3055. ];
  3056. $this->assertEquals($expected, $results->toList());
  3057. $this->expectException(InvalidArgumentException::class);
  3058. $this->expectExceptionMessage('The `Tags` association is not defined on `Articles`.');
  3059. $table
  3060. ->find()
  3061. ->disableHydration()
  3062. ->contain('Tags')
  3063. ->leftJoinWith('Tags')
  3064. ->all();
  3065. }
  3066. /**
  3067. * Tests innerJoinWith()
  3068. */
  3069. public function testInnerJoinWith(): void
  3070. {
  3071. $table = $this->getTableLocator()->get('authors');
  3072. $table->hasMany('articles');
  3073. $results = $table
  3074. ->find()
  3075. ->innerJoinWith('articles', function ($q) {
  3076. return $q->where(['articles.title' => 'Third Article']);
  3077. });
  3078. $expected = [
  3079. [
  3080. 'id' => 1,
  3081. 'name' => 'mariano',
  3082. ],
  3083. ];
  3084. $this->assertEquals($expected, $results->enableHydration(false)->toArray());
  3085. }
  3086. /**
  3087. * Tests innerJoinWith() with nested associations
  3088. */
  3089. public function testInnerJoinWithNested(): void
  3090. {
  3091. $table = $this->getTableLocator()->get('authors');
  3092. $articles = $table->hasMany('articles');
  3093. $articles->belongsToMany('tags');
  3094. $results = $table
  3095. ->find()
  3096. ->innerJoinWith('articles.tags', function ($q) {
  3097. return $q->where(['tags.name' => 'tag3']);
  3098. });
  3099. $expected = [
  3100. [
  3101. 'id' => 3,
  3102. 'name' => 'larry',
  3103. ],
  3104. ];
  3105. $this->assertEquals($expected, $results->enableHydration(false)->toArray());
  3106. }
  3107. /**
  3108. * Tests innerJoinWith() with select
  3109. */
  3110. public function testInnerJoinWithSelect(): void
  3111. {
  3112. $table = $this->getTableLocator()->get('authors');
  3113. $table->hasMany('articles');
  3114. $results = $table
  3115. ->find()
  3116. ->enableAutoFields()
  3117. ->innerJoinWith('articles', function ($q) {
  3118. return $q->select(['id', 'author_id', 'title', 'body', 'published']);
  3119. })
  3120. ->toArray();
  3121. $expected = $table
  3122. ->find()
  3123. ->matching('articles')
  3124. ->toArray();
  3125. $this->assertEquals($expected, $results);
  3126. }
  3127. /**
  3128. * Tests contain() in query returned by innerJoinWith throws exception.
  3129. */
  3130. public function testInnerJoinWithContain(): void
  3131. {
  3132. $comments = $this->getTableLocator()->get('Comments');
  3133. $articles = $comments->belongsTo('Articles');
  3134. $articles->hasOne('ArticlesTranslations');
  3135. $this->expectException(DatabaseException::class);
  3136. $this->expectExceptionMessage('`Articles` association cannot contain() associations when using JOIN strategy');
  3137. $comments->find()
  3138. ->innerJoinWith('Articles', function (Query $q) {
  3139. return $q
  3140. ->contain('ArticlesTranslations')
  3141. ->where(['ArticlesTranslations.title' => 'Titel #1']);
  3142. })
  3143. ->sql();
  3144. }
  3145. /**
  3146. * Tests notMatching() with and without conditions
  3147. */
  3148. public function testNotMatching(): void
  3149. {
  3150. $table = $this->getTableLocator()->get('authors');
  3151. $table->hasMany('articles');
  3152. $results = $table->find()
  3153. ->enableHydration(false)
  3154. ->notMatching('articles')
  3155. ->order(['authors.id'])
  3156. ->toArray();
  3157. $expected = [
  3158. ['id' => 2, 'name' => 'nate'],
  3159. ['id' => 4, 'name' => 'garrett'],
  3160. ];
  3161. $this->assertEquals($expected, $results);
  3162. $results = $table->find()
  3163. ->enableHydration(false)
  3164. ->notMatching('articles', function ($q) {
  3165. return $q->where(['articles.author_id' => 1]);
  3166. })
  3167. ->order(['authors.id'])
  3168. ->toArray();
  3169. $expected = [
  3170. ['id' => 2, 'name' => 'nate'],
  3171. ['id' => 3, 'name' => 'larry'],
  3172. ['id' => 4, 'name' => 'garrett'],
  3173. ];
  3174. $this->assertEquals($expected, $results);
  3175. }
  3176. /**
  3177. * Tests notMatching() with a belongsToMany association
  3178. */
  3179. public function testNotMatchingBelongsToMany(): void
  3180. {
  3181. $table = $this->getTableLocator()->get('articles');
  3182. $table->belongsToMany('tags');
  3183. $results = $table->find()
  3184. ->enableHydration(false)
  3185. ->notMatching('tags', function ($q) {
  3186. return $q->where(['tags.name' => 'tag2']);
  3187. });
  3188. $results = $results->toArray();
  3189. $expected = [
  3190. [
  3191. 'id' => 2,
  3192. 'author_id' => 3,
  3193. 'title' => 'Second Article',
  3194. 'body' => 'Second Article Body',
  3195. 'published' => 'Y',
  3196. ],
  3197. [
  3198. 'id' => 3,
  3199. 'author_id' => 1,
  3200. 'title' => 'Third Article',
  3201. 'body' => 'Third Article Body',
  3202. 'published' => 'Y',
  3203. ],
  3204. ];
  3205. $this->assertEquals($expected, $results);
  3206. }
  3207. /**
  3208. * Tests notMatching() with a deeply nested belongsToMany association.
  3209. */
  3210. public function testNotMatchingDeep(): void
  3211. {
  3212. $table = $this->getTableLocator()->get('authors');
  3213. $articles = $table->hasMany('articles');
  3214. $articles->belongsToMany('tags');
  3215. $results = $table->find()
  3216. ->enableHydration(false)
  3217. ->select('authors.id')
  3218. ->notMatching('articles.tags', function ($q) {
  3219. return $q->where(['tags.name' => 'tag3']);
  3220. })
  3221. ->distinct(['authors.id']);
  3222. $this->assertEquals([1, 2, 4], $results->all()->extract('id')->toList());
  3223. $results = $table->find()
  3224. ->enableHydration(false)
  3225. ->notMatching('articles.tags', function ($q) {
  3226. return $q->where(['tags.name' => 'tag3']);
  3227. })
  3228. ->matching('articles')
  3229. ->distinct(['authors.id']);
  3230. $this->assertEquals([1], $results->all()->extract('id')->toList());
  3231. }
  3232. /**
  3233. * Tests that it is possible to nest a notMatching call inside another
  3234. * eagerloader function.
  3235. */
  3236. public function testNotMatchingNested(): void
  3237. {
  3238. $table = $this->getTableLocator()->get('authors');
  3239. $articles = $table->hasMany('articles');
  3240. $articles->belongsToMany('tags');
  3241. $results = $table->find()
  3242. ->enableHydration(false)
  3243. ->matching('articles', function (Query $q) {
  3244. return $q->notMatching('tags', function (Query $q) {
  3245. return $q->where(['tags.name' => 'tag3']);
  3246. });
  3247. })
  3248. ->order(['authors.id' => 'ASC', 'articles.id' => 'ASC']);
  3249. $expected = [
  3250. 'id' => 1,
  3251. 'name' => 'mariano',
  3252. '_matchingData' => [
  3253. 'articles' => [
  3254. 'id' => 1,
  3255. 'author_id' => 1,
  3256. 'title' => 'First Article',
  3257. 'body' => 'First Article Body',
  3258. 'published' => 'Y',
  3259. ],
  3260. ],
  3261. ];
  3262. $this->assertSame($expected, $results->first());
  3263. }
  3264. /**
  3265. * Test to see that the excluded fields are not in the select clause
  3266. */
  3267. public function testSelectAllExcept(): void
  3268. {
  3269. $table = $this->getTableLocator()->get('Articles');
  3270. $result = $table
  3271. ->find()
  3272. ->selectAllExcept($table, ['body']);
  3273. $selectedFields = $result->clause('select');
  3274. $expected = [
  3275. 'Articles__id' => 'Articles.id',
  3276. 'Articles__author_id' => 'Articles.author_id',
  3277. 'Articles__title' => 'Articles.title',
  3278. 'Articles__published' => 'Articles.published',
  3279. ];
  3280. $this->assertEquals($expected, $selectedFields);
  3281. }
  3282. /**
  3283. * Test that the excluded fields are not included
  3284. * in the final query result.
  3285. */
  3286. public function testSelectAllExceptWithContains(): void
  3287. {
  3288. $table = $this->getTableLocator()->get('Articles');
  3289. $table->hasMany('Comments');
  3290. $table->belongsTo('Authors');
  3291. $result = $table
  3292. ->find()
  3293. ->contain([
  3294. 'Comments' => function (Query $query) use ($table) {
  3295. return $query->selectAllExcept($table->Comments, ['published']);
  3296. },
  3297. ])
  3298. ->selectAllExcept($table, ['body'])
  3299. ->first();
  3300. $this->assertNull($result->comments[0]->published);
  3301. $this->assertNull($result->body);
  3302. $this->assertNotEmpty($result->id);
  3303. $this->assertNotEmpty($result->comments[0]->id);
  3304. }
  3305. /**
  3306. * Test what happens if you call selectAllExcept() more
  3307. * than once.
  3308. */
  3309. public function testSelectAllExceptWithMulitpleCalls(): void
  3310. {
  3311. $table = $this->getTableLocator()->get('Articles');
  3312. $result = $table
  3313. ->find()
  3314. ->selectAllExcept($table, ['body'])
  3315. ->selectAllExcept($table, ['published']);
  3316. $selectedFields = $result->clause('select');
  3317. $expected = [
  3318. 'Articles__id' => 'Articles.id',
  3319. 'Articles__author_id' => 'Articles.author_id',
  3320. 'Articles__title' => 'Articles.title',
  3321. 'Articles__published' => 'Articles.published',
  3322. 'Articles__body' => 'Articles.body',
  3323. ];
  3324. $this->assertEquals($expected, $selectedFields);
  3325. $result = $table
  3326. ->find()
  3327. ->selectAllExcept($table, ['body'])
  3328. ->selectAllExcept($table, ['published', 'body']);
  3329. $selectedFields = $result->clause('select');
  3330. $expected = [
  3331. 'Articles__id' => 'Articles.id',
  3332. 'Articles__author_id' => 'Articles.author_id',
  3333. 'Articles__title' => 'Articles.title',
  3334. 'Articles__published' => 'Articles.published',
  3335. ];
  3336. $this->assertEquals($expected, $selectedFields);
  3337. $result = $table
  3338. ->find()
  3339. ->selectAllExcept($table, ['body'])
  3340. ->selectAllExcept($table, ['published', 'body'], true);
  3341. $selectedFields = $result->clause('select');
  3342. $expected = [
  3343. 'Articles__id' => 'Articles.id',
  3344. 'Articles__author_id' => 'Articles.author_id',
  3345. 'Articles__title' => 'Articles.title',
  3346. ];
  3347. $this->assertEquals($expected, $selectedFields);
  3348. }
  3349. /**
  3350. * Tests that using Having on an aggregated field returns the correct result
  3351. * model in the query
  3352. */
  3353. public function testHavingOnAnAggregatedField(): void
  3354. {
  3355. $post = $this->getTableLocator()->get('posts');
  3356. $query = new Query($this->connection, $post);
  3357. $results = $query
  3358. ->select([
  3359. 'posts.author_id',
  3360. 'post_count' => $query->func()->count('posts.id'),
  3361. ])
  3362. ->group(['posts.author_id'])
  3363. ->having([$query->newExpr()->gte('post_count', 2, 'integer')])
  3364. ->enableHydration(false)
  3365. ->toArray();
  3366. $expected = [
  3367. [
  3368. 'author_id' => 1,
  3369. 'post_count' => 2,
  3370. ],
  3371. ];
  3372. $this->assertEquals($expected, $results);
  3373. }
  3374. /**
  3375. * Tests ORM query using with CTE.
  3376. */
  3377. public function testWith(): void
  3378. {
  3379. $this->skipIf(
  3380. !$this->connection->getDriver()->supports(DriverFeatureEnum::CTE),
  3381. 'The current driver does not support common table expressions.'
  3382. );
  3383. $this->skipIf(
  3384. (
  3385. $this->connection->getDriver() instanceof Mysql ||
  3386. $this->connection->getDriver() instanceof Sqlite
  3387. ) &&
  3388. !$this->connection->getDriver()->supports(DriverFeatureEnum::WINDOW),
  3389. 'The current driver does not support window functions.'
  3390. );
  3391. $table = $this->getTableLocator()->get('Articles');
  3392. $cteQuery = $table
  3393. ->find()
  3394. ->select(function (Query $query) use ($table) {
  3395. $columns = $table->getSchema()->columns();
  3396. return array_combine($columns, $columns) + [
  3397. 'row_num' => $query
  3398. ->func()
  3399. ->rowNumber()
  3400. ->over()
  3401. ->partition('author_id')
  3402. ->order(['id' => 'ASC']),
  3403. ];
  3404. });
  3405. $query = $table
  3406. ->find()
  3407. ->with(function (CommonTableExpression $cte) use ($cteQuery) {
  3408. return $cte
  3409. ->name('cte')
  3410. ->query($cteQuery);
  3411. })
  3412. ->select(['row_num'])
  3413. ->enableAutoFields()
  3414. ->from([$table->getAlias() => 'cte'])
  3415. ->where(['row_num' => 1], ['row_num' => 'integer'])
  3416. ->order(['id' => 'ASC'])
  3417. ->disableHydration();
  3418. $expected = [
  3419. [
  3420. 'id' => 1,
  3421. 'author_id' => 1,
  3422. 'title' => 'First Article',
  3423. 'body' => 'First Article Body',
  3424. 'published' => 'Y',
  3425. 'row_num' => '1',
  3426. ],
  3427. [
  3428. 'id' => 2,
  3429. 'author_id' => 3,
  3430. 'title' => 'Second Article',
  3431. 'body' => 'Second Article Body',
  3432. 'published' => 'Y',
  3433. 'row_num' => '1',
  3434. ],
  3435. ];
  3436. $this->assertEquals($expected, $query->toArray());
  3437. }
  3438. /**
  3439. * Tests that queries that fetch associated data in separate queries do properly
  3440. * inherit the hydration and results casting mode of the parent query.
  3441. */
  3442. public function testSelectLoaderAssociationsInheritHydrationAndResultsCastingMode(): void
  3443. {
  3444. $articles = $this->getTableLocator()->get('Articles');
  3445. $tags = $articles->belongsToMany('Tags');
  3446. $tags->belongsToMany('Articles');
  3447. $comments = $articles->hasMany('Comments');
  3448. $comments
  3449. ->belongsTo('Articles')
  3450. ->setStrategy(BelongsTo::STRATEGY_SELECT);
  3451. $articles
  3452. ->find()
  3453. ->contain('Comments', function (Query $query) {
  3454. $this->assertFalse($query->isHydrationEnabled());
  3455. $this->assertFalse($query->isResultsCastingEnabled());
  3456. return $query;
  3457. })
  3458. ->contain('Comments.Articles', function (Query $query) {
  3459. $this->assertFalse($query->isHydrationEnabled());
  3460. $this->assertFalse($query->isResultsCastingEnabled());
  3461. return $query;
  3462. })
  3463. ->contain('Comments.Articles.Tags', function (Query $query) {
  3464. $this->assertFalse($query->isHydrationEnabled());
  3465. $this->assertFalse($query->isResultsCastingEnabled());
  3466. return $query
  3467. ->enableHydration()
  3468. ->enableResultsCasting();
  3469. })
  3470. ->contain('Comments.Articles.Tags.Articles', function (Query $query) {
  3471. $this->assertTrue($query->isHydrationEnabled());
  3472. $this->assertTrue($query->isResultsCastingEnabled());
  3473. return $query;
  3474. })
  3475. ->disableHydration()
  3476. ->disableResultsCasting()
  3477. ->firstOrFail();
  3478. }
  3479. /**
  3480. * Tests that passing a ORM query as an argument wraps the query SQL into parentheses.
  3481. */
  3482. public function testFunctionWithOrmQuery(): void
  3483. {
  3484. $query = $this->getTableLocator()->get('Articles')
  3485. ->setSchema(['column' => 'integer'])
  3486. ->find()
  3487. ->select(['column']);
  3488. $binder = new ValueBinder();
  3489. $function = new FunctionExpression('MyFunction', [$query]);
  3490. $this->assertSame(
  3491. 'MyFunction((SELECT Articles.column AS Articles__column FROM articles Articles))',
  3492. preg_replace('/[`"\[\]]/', '', $function->sql($binder))
  3493. );
  3494. }
  3495. }