QueryTest.php 134 KB

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