SelectQueryTest.php 129 KB

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