QueryTest.php 129 KB

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