SelectQueryTest.php 129 KB

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