QueryTest.php 129 KB

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