SelectQueryTest.php 127 KB

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