SelectQueryTest.php 129 KB

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