SelectQueryTest.php 129 KB

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