SelectQueryTest.php 128 KB

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