QueryTest.php 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  14. */
  15. namespace Cake\Test\TestCase\ORM;
  16. use Cake\Database\Expression\IdentifierExpression;
  17. use Cake\Database\Expression\OrderByExpression;
  18. use Cake\Database\Expression\QueryExpression;
  19. use Cake\Datasource\ConnectionManager;
  20. use Cake\ORM\Query;
  21. use Cake\ORM\ResultSet;
  22. use Cake\ORM\Table;
  23. use Cake\ORM\TableRegistry;
  24. use Cake\TestSuite\TestCase;
  25. /**
  26. * Tests Query class
  27. *
  28. */
  29. class QueryTest extends TestCase {
  30. /**
  31. * Fixture to be used
  32. *
  33. * @var array
  34. */
  35. public $fixtures = ['core.article', 'core.author', 'core.tag',
  36. 'core.articles_tag', 'core.post'];
  37. /**
  38. * setUp method
  39. *
  40. * @return void
  41. */
  42. public function setUp() {
  43. parent::setUp();
  44. $this->connection = ConnectionManager::get('test');
  45. $schema = [
  46. 'id' => ['type' => 'integer'],
  47. '_constraints' => [
  48. 'primary' => ['type' => 'primary', 'columns' => ['id']]
  49. ]
  50. ];
  51. $schema1 = [
  52. 'id' => ['type' => 'integer'],
  53. 'name' => ['type' => 'string'],
  54. 'phone' => ['type' => 'string'],
  55. '_constraints' => [
  56. 'primary' => ['type' => 'primary', 'columns' => ['id']]
  57. ]
  58. ];
  59. $schema2 = [
  60. 'id' => ['type' => 'integer'],
  61. 'total' => ['type' => 'string'],
  62. 'placed' => ['type' => 'datetime'],
  63. '_constraints' => [
  64. 'primary' => ['type' => 'primary', 'columns' => ['id']]
  65. ]
  66. ];
  67. $this->table = $table = TableRegistry::get('foo', ['schema' => $schema]);
  68. $clients = TableRegistry::get('clients', ['schema' => $schema1]);
  69. $orders = TableRegistry::get('orders', ['schema' => $schema2]);
  70. $companies = TableRegistry::get('companies', ['schema' => $schema, 'table' => 'organizations']);
  71. $orderTypes = TableRegistry::get('orderTypes', ['schema' => $schema]);
  72. $stuff = TableRegistry::get('stuff', ['schema' => $schema, 'table' => 'things']);
  73. $stuffTypes = TableRegistry::get('stuffTypes', ['schema' => $schema]);
  74. $categories = TableRegistry::get('categories', ['schema' => $schema]);
  75. $table->belongsTo('clients');
  76. $clients->hasOne('orders');
  77. $clients->belongsTo('companies');
  78. $orders->belongsTo('orderTypes');
  79. $orders->hasOne('stuff');
  80. $stuff->belongsTo('stuffTypes');
  81. $companies->belongsTo('categories');
  82. }
  83. /**
  84. * tearDown method
  85. *
  86. * @return void
  87. */
  88. public function tearDown() {
  89. parent::tearDown();
  90. TableRegistry::clear();
  91. }
  92. /**
  93. * Tests that results are grouped correctly when using contain()
  94. * and results are not hydrated
  95. *
  96. * @return void
  97. */
  98. public function testContainResultFetchingOneLevel() {
  99. $table = TableRegistry::get('articles', ['table' => 'articles']);
  100. $table->belongsTo('authors');
  101. $query = new Query($this->connection, $table);
  102. $results = $query->select()
  103. ->contain('authors')
  104. ->hydrate(false)
  105. ->order(['articles.id' => 'asc'])
  106. ->toArray();
  107. $expected = [
  108. [
  109. 'id' => 1,
  110. 'title' => 'First Article',
  111. 'body' => 'First Article Body',
  112. 'author_id' => 1,
  113. 'published' => 'Y',
  114. 'author' => [
  115. 'id' => 1,
  116. 'name' => 'mariano'
  117. ]
  118. ],
  119. [
  120. 'id' => 2,
  121. 'title' => 'Second Article',
  122. 'body' => 'Second Article Body',
  123. 'author_id' => 3,
  124. 'published' => 'Y',
  125. 'author' => [
  126. 'id' => 3,
  127. 'name' => 'larry'
  128. ]
  129. ],
  130. [
  131. 'id' => 3,
  132. 'title' => 'Third Article',
  133. 'body' => 'Third Article Body',
  134. 'author_id' => 1,
  135. 'published' => 'Y',
  136. 'author' => [
  137. 'id' => 1,
  138. 'name' => 'mariano'
  139. ]
  140. ],
  141. ];
  142. $this->assertEquals($expected, $results);
  143. }
  144. /**
  145. * Data provider for the two types of strategies HasMany implements
  146. *
  147. * @return void
  148. */
  149. public function strategiesProvider() {
  150. return [['subquery'], ['select']];
  151. }
  152. /**
  153. * Tests that HasMany associations are correctly eager loaded and results
  154. * correctly nested when no hydration is used
  155. * Also that the query object passes the correct parent model keys to the
  156. * association objects in order to perform eager loading with select strategy
  157. *
  158. * @dataProvider strategiesProvider
  159. * @return void
  160. */
  161. public function testHasManyEagerLoadingNoHydration($strategy) {
  162. $table = TableRegistry::get('authors');
  163. TableRegistry::get('articles');
  164. $table->hasMany('articles', [
  165. 'propertyName' => 'articles',
  166. 'strategy' => $strategy,
  167. 'sort' => ['articles.id' => 'asc']
  168. ]);
  169. $query = new Query($this->connection, $table);
  170. $results = $query->select()
  171. ->contain('articles')
  172. ->hydrate(false)
  173. ->toArray();
  174. $expected = [
  175. [
  176. 'id' => 1,
  177. 'name' => 'mariano',
  178. 'articles' => [
  179. [
  180. 'id' => 1,
  181. 'title' => 'First Article',
  182. 'body' => 'First Article Body',
  183. 'author_id' => 1,
  184. 'published' => 'Y',
  185. ],
  186. [
  187. 'id' => 3,
  188. 'title' => 'Third Article',
  189. 'body' => 'Third Article Body',
  190. 'author_id' => 1,
  191. 'published' => 'Y',
  192. ],
  193. ]
  194. ],
  195. [
  196. 'id' => 2,
  197. 'name' => 'nate',
  198. ],
  199. [
  200. 'id' => 3,
  201. 'name' => 'larry',
  202. 'articles' => [
  203. [
  204. 'id' => 2,
  205. 'title' => 'Second Article',
  206. 'body' => 'Second Article Body',
  207. 'author_id' => 3,
  208. 'published' => 'Y'
  209. ]
  210. ]
  211. ],
  212. [
  213. 'id' => 4,
  214. 'name' => 'garrett',
  215. ]
  216. ];
  217. $this->assertEquals($expected, $results);
  218. $results = $query->repository($table)
  219. ->select()
  220. ->contain(['articles' => ['conditions' => ['id' => 2]]])
  221. ->hydrate(false)
  222. ->toArray();
  223. unset($expected[0]['articles']);
  224. $this->assertEquals($expected, $results);
  225. $this->assertEquals($table->association('articles')->strategy(), $strategy);
  226. }
  227. /**
  228. * Tests that it is possible to count results containing hasMany associations
  229. * both hydrating and not hydrating the results.
  230. *
  231. * @dataProvider strategiesProvider
  232. * @return void
  233. */
  234. public function testHasManyEagerLoadingCount($strategy) {
  235. $table = TableRegistry::get('authors');
  236. TableRegistry::get('articles');
  237. $table->hasMany('articles', [
  238. 'property' => 'articles',
  239. 'strategy' => $strategy,
  240. 'sort' => ['articles.id' => 'asc']
  241. ]);
  242. $query = new Query($this->connection, $table);
  243. $query = $query->select()
  244. ->contain('articles');
  245. $expected = 4;
  246. $results = $query->hydrate(false)
  247. ->count();
  248. $this->assertEquals($expected, $results);
  249. $results = $query->hydrate(true)
  250. ->count();
  251. $this->assertEquals($expected, $results);
  252. }
  253. /**
  254. * Tests that it is possible to set fields & order in a hasMany result set
  255. *
  256. * @dataProvider strategiesProvider
  257. * @return void
  258. **/
  259. public function testHasManyEagerLoadingFieldsAndOrderNoHydration($strategy) {
  260. $table = TableRegistry::get('authors');
  261. TableRegistry::get('articles');
  262. $table->hasMany('articles', ['propertyName' => 'articles'] + compact('strategy'));
  263. $query = new Query($this->connection, $table);
  264. $results = $query->select()
  265. ->contain([
  266. 'articles' => [
  267. 'fields' => ['title', 'author_id'],
  268. 'sort' => ['id' => 'DESC']
  269. ]
  270. ])
  271. ->hydrate(false)
  272. ->toArray();
  273. $expected = [
  274. [
  275. 'id' => 1,
  276. 'name' => 'mariano',
  277. 'articles' => [
  278. ['title' => 'Third Article', 'author_id' => 1],
  279. ['title' => 'First Article', 'author_id' => 1],
  280. ]
  281. ],
  282. [
  283. 'id' => 2,
  284. 'name' => 'nate',
  285. ],
  286. [
  287. 'id' => 3,
  288. 'name' => 'larry',
  289. 'articles' => [
  290. ['title' => 'Second Article', 'author_id' => 3],
  291. ]
  292. ],
  293. [
  294. 'id' => 4,
  295. 'name' => 'garrett',
  296. ],
  297. ];
  298. $this->assertEquals($expected, $results);
  299. }
  300. /**
  301. * Tests that deep associations can be eagerly loaded
  302. *
  303. * @dataProvider strategiesProvider
  304. * @return void
  305. */
  306. public function testHasManyEagerLoadingDeep($strategy) {
  307. $table = TableRegistry::get('authors');
  308. $article = TableRegistry::get('articles');
  309. $table->hasMany('articles', [
  310. 'propertyName' => 'articles',
  311. 'strategy' => $strategy,
  312. 'sort' => ['articles.id' => 'asc']
  313. ]);
  314. $article->belongsTo('authors');
  315. $query = new Query($this->connection, $table);
  316. $results = $query->select()
  317. ->contain(['articles' => ['authors']])
  318. ->hydrate(false)
  319. ->toArray();
  320. $expected = [
  321. [
  322. 'id' => 1,
  323. 'name' => 'mariano',
  324. 'articles' => [
  325. [
  326. 'id' => 1,
  327. 'title' => 'First Article',
  328. 'author_id' => 1,
  329. 'body' => 'First Article Body',
  330. 'published' => 'Y',
  331. 'author' => ['id' => 1, 'name' => 'mariano']
  332. ],
  333. [
  334. 'id' => 3,
  335. 'title' => 'Third Article',
  336. 'author_id' => 1,
  337. 'body' => 'Third Article Body',
  338. 'published' => 'Y',
  339. 'author' => ['id' => 1, 'name' => 'mariano']
  340. ],
  341. ]
  342. ],
  343. [
  344. 'id' => 2,
  345. 'name' => 'nate'
  346. ],
  347. [
  348. 'id' => 3,
  349. 'name' => 'larry',
  350. 'articles' => [
  351. [
  352. 'id' => 2,
  353. 'title' => 'Second Article',
  354. 'author_id' => 3,
  355. 'body' => 'Second Article Body',
  356. 'published' => 'Y',
  357. 'author' => ['id' => 3, 'name' => 'larry']
  358. ],
  359. ]
  360. ],
  361. [
  362. 'id' => 4,
  363. 'name' => 'garrett'
  364. ]
  365. ];
  366. $this->assertEquals($expected, $results);
  367. }
  368. /**
  369. * Tests that hasMany associations can be loaded even when related to a secondary
  370. * model in the query
  371. *
  372. * @dataProvider strategiesProvider
  373. * @return void
  374. */
  375. public function testHasManyEagerLoadingFromSecondaryTable($strategy) {
  376. $author = TableRegistry::get('authors');
  377. $article = TableRegistry::get('articles');
  378. $post = TableRegistry::get('posts');
  379. $author->hasMany('posts', compact('strategy'));
  380. $article->belongsTo('authors');
  381. $query = new Query($this->connection, $article);
  382. $results = $query->select()
  383. ->contain(['authors' => ['posts']])
  384. ->order(['articles.id' => 'ASC'])
  385. ->hydrate(false)
  386. ->toArray();
  387. $expected = [
  388. [
  389. 'id' => 1,
  390. 'title' => 'First Article',
  391. 'body' => 'First Article Body',
  392. 'author_id' => 1,
  393. 'published' => 'Y',
  394. 'author' => [
  395. 'id' => 1,
  396. 'name' => 'mariano',
  397. 'posts' => [
  398. [
  399. 'id' => '1',
  400. 'title' => 'First Post',
  401. 'body' => 'First Post Body',
  402. 'author_id' => 1,
  403. 'published' => 'Y',
  404. ],
  405. [
  406. 'id' => '3',
  407. 'title' => 'Third Post',
  408. 'body' => 'Third Post Body',
  409. 'author_id' => 1,
  410. 'published' => 'Y',
  411. ],
  412. ]
  413. ]
  414. ],
  415. [
  416. 'id' => 2,
  417. 'title' => 'Second Article',
  418. 'body' => 'Second Article Body',
  419. 'author_id' => 3,
  420. 'published' => 'Y',
  421. 'author' => [
  422. 'id' => 3,
  423. 'name' => 'larry',
  424. 'posts' => [
  425. [
  426. 'id' => 2,
  427. 'title' => 'Second Post',
  428. 'body' => 'Second Post Body',
  429. 'author_id' => 3,
  430. 'published' => 'Y',
  431. ]
  432. ]
  433. ]
  434. ],
  435. [
  436. 'id' => 3,
  437. 'title' => 'Third Article',
  438. 'body' => 'Third Article Body',
  439. 'author_id' => 1,
  440. 'published' => 'Y',
  441. 'author' => [
  442. 'id' => 1,
  443. 'name' => 'mariano',
  444. 'posts' => [
  445. [
  446. 'id' => '1',
  447. 'title' => 'First Post',
  448. 'body' => 'First Post Body',
  449. 'author_id' => 1,
  450. 'published' => 'Y',
  451. ],
  452. [
  453. 'id' => '3',
  454. 'title' => 'Third Post',
  455. 'body' => 'Third Post Body',
  456. 'author_id' => 1,
  457. 'published' => 'Y',
  458. ],
  459. ]
  460. ]
  461. ],
  462. ];
  463. $this->assertEquals($expected, $results);
  464. }
  465. /**
  466. * Tests that BelongsToMany associations are correctly eager loaded.
  467. * Also that the query object passes the correct parent model keys to the
  468. * association objects in order to perform eager loading with select strategy
  469. *
  470. * @dataProvider strategiesProvider
  471. * @return void
  472. **/
  473. public function testBelongsToManyEagerLoadingNoHydration($strategy) {
  474. $table = TableRegistry::get('Articles');
  475. TableRegistry::get('Tags');
  476. TableRegistry::get('ArticlesTags', [
  477. 'table' => 'articles_tags'
  478. ]);
  479. $table->belongsToMany('Tags', ['strategy' => $strategy]);
  480. $query = new Query($this->connection, $table);
  481. $results = $query->select()->contain('Tags')->hydrate(false)->toArray();
  482. $expected = [
  483. [
  484. 'id' => 1,
  485. 'author_id' => 1,
  486. 'title' => 'First Article',
  487. 'body' => 'First Article Body',
  488. 'published' => 'Y',
  489. 'tags' => [
  490. [
  491. 'id' => 1,
  492. 'name' => 'tag1',
  493. '_joinData' => ['article_id' => 1, 'tag_id' => 1]
  494. ],
  495. [
  496. 'id' => 2,
  497. 'name' => 'tag2',
  498. '_joinData' => ['article_id' => 1, 'tag_id' => 2]
  499. ]
  500. ]
  501. ],
  502. [
  503. 'id' => 2,
  504. 'title' => 'Second Article',
  505. 'body' => 'Second Article Body',
  506. 'author_id' => 3,
  507. 'published' => 'Y',
  508. 'tags' => [
  509. [
  510. 'id' => 1,
  511. 'name' => 'tag1',
  512. '_joinData' => ['article_id' => 2, 'tag_id' => 1]
  513. ],
  514. [
  515. 'id' => 3,
  516. 'name' => 'tag3',
  517. '_joinData' => ['article_id' => 2, 'tag_id' => 3]
  518. ]
  519. ]
  520. ],
  521. [
  522. 'id' => 3,
  523. 'title' => 'Third Article',
  524. 'body' => 'Third Article Body',
  525. 'author_id' => 1,
  526. 'published' => 'Y',
  527. ],
  528. ];
  529. $this->assertEquals($expected, $results);
  530. $results = $query->select()
  531. ->contain(['Tags' => ['conditions' => ['id' => 3]]])
  532. ->hydrate(false)
  533. ->toArray();
  534. $expected = [
  535. [
  536. 'id' => 1,
  537. 'author_id' => 1,
  538. 'title' => 'First Article',
  539. 'body' => 'First Article Body',
  540. 'published' => 'Y',
  541. ],
  542. [
  543. 'id' => 2,
  544. 'title' => 'Second Article',
  545. 'body' => 'Second Article Body',
  546. 'author_id' => 3,
  547. 'published' => 'Y',
  548. 'tags' => [
  549. [
  550. 'id' => 3,
  551. 'name' => 'tag3',
  552. '_joinData' => ['article_id' => 2, 'tag_id' => 3]
  553. ]
  554. ]
  555. ],
  556. [
  557. 'id' => 3,
  558. 'title' => 'Third Article',
  559. 'body' => 'Third Article Body',
  560. 'author_id' => 1,
  561. 'published' => 'Y',
  562. ],
  563. ];
  564. $this->assertEquals($expected, $results);
  565. $this->assertEquals($table->association('Tags')->strategy(), $strategy);
  566. }
  567. /**
  568. * Tests that tables results can be filtered by the result of a HasMany
  569. *
  570. * @return void
  571. */
  572. public function testFilteringByHasManyNoHydration() {
  573. $query = new Query($this->connection, $this->table);
  574. $table = TableRegistry::get('authors');
  575. TableRegistry::get('articles');
  576. $table->hasMany('articles');
  577. $results = $query->repository($table)
  578. ->select()
  579. ->hydrate(false)
  580. ->matching('articles', function($q) {
  581. return $q->where(['articles.id' => 2]);
  582. })
  583. ->toArray();
  584. $expected = [
  585. [
  586. 'id' => 3,
  587. 'name' => 'larry',
  588. 'articles' => [
  589. 'id' => 2,
  590. 'title' => 'Second Article',
  591. 'body' => 'Second Article Body',
  592. 'author_id' => 3,
  593. 'published' => 'Y',
  594. ]
  595. ]
  596. ];
  597. $this->assertEquals($expected, $results);
  598. }
  599. /**
  600. * Tests that BelongsToMany associations are correctly eager loaded.
  601. * Also that the query object passes the correct parent model keys to the
  602. * association objects in order to perform eager loading with select strategy
  603. *
  604. * @return void
  605. **/
  606. public function testFilteringByBelongsToManyNoHydration() {
  607. $query = new Query($this->connection, $this->table);
  608. $table = TableRegistry::get('Articles');
  609. TableRegistry::get('Tags');
  610. TableRegistry::get('ArticlesTags', [
  611. 'table' => 'articles_tags'
  612. ]);
  613. $table->belongsToMany('Tags');
  614. $results = $query->repository($table)->select()
  615. ->matching('Tags', function($q) {
  616. return $q->where(['Tags.id' => 3]);
  617. })
  618. ->hydrate(false)
  619. ->toArray();
  620. $expected = [
  621. [
  622. 'id' => 2,
  623. 'author_id' => 3,
  624. 'title' => 'Second Article',
  625. 'body' => 'Second Article Body',
  626. 'published' => 'Y',
  627. 'tags' => [
  628. 'id' => 3,
  629. 'name' => 'tag3',
  630. '_joinData' => ['article_id' => 2, 'tag_id' => 3]
  631. ]
  632. ]
  633. ];
  634. $this->assertEquals($expected, $results);
  635. $query = new Query($this->connection, $table);
  636. $results = $query->select()
  637. ->matching('Tags', function($q) {
  638. return $q->where(['Tags.name' => 'tag2']);
  639. })
  640. ->hydrate(false)
  641. ->toArray();
  642. $expected = [
  643. [
  644. 'id' => 1,
  645. 'title' => 'First Article',
  646. 'body' => 'First Article Body',
  647. 'author_id' => 1,
  648. 'published' => 'Y',
  649. 'tags' => [
  650. 'id' => 2,
  651. 'name' => 'tag2',
  652. '_joinData' => ['article_id' => 1, 'tag_id' => 2]
  653. ]
  654. ]
  655. ];
  656. $this->assertEquals($expected, $results);
  657. }
  658. /**
  659. * Tests that it is possible to filter by deep associations
  660. *
  661. * @return void
  662. */
  663. public function testMatchingDotNotation() {
  664. $query = new Query($this->connection, $this->table);
  665. $table = TableRegistry::get('authors');
  666. TableRegistry::get('articles');
  667. $table->hasMany('articles');
  668. TableRegistry::get('articles')->belongsToMany('tags');
  669. $results = $query->repository($table)
  670. ->select()
  671. ->hydrate(false)
  672. ->matching('articles.tags', function($q) {
  673. return $q->where(['tags.id' => 2]);
  674. })
  675. ->toArray();
  676. $expected = [
  677. [
  678. 'id' => 1,
  679. 'name' => 'mariano',
  680. 'articles' => [
  681. 'id' => 1,
  682. 'title' => 'First Article',
  683. 'body' => 'First Article Body',
  684. 'author_id' => 1,
  685. 'published' => 'Y',
  686. 'tags' => [
  687. 'id' => 2,
  688. 'name' => 'tag2',
  689. '_joinData' => ['article_id' => 1, 'tag_id' => 2]
  690. ]
  691. ]
  692. ]
  693. ];
  694. $this->assertEquals($expected, $results);
  695. }
  696. /**
  697. * Test setResult()
  698. *
  699. * @return void
  700. */
  701. public function testSetResult() {
  702. $query = new Query($this->connection, $this->table);
  703. $stmt = $this->getMock('Cake\Database\StatementInterface');
  704. $results = new ResultSet($query, $stmt);
  705. $query->setResult($results);
  706. $this->assertSame($results, $query->all());
  707. }
  708. /**
  709. * Tests that applying array options to a query will convert them
  710. * to equivalent function calls with the correspondent array values
  711. *
  712. * @return void
  713. */
  714. public function testApplyOptions() {
  715. $options = [
  716. 'fields' => ['field_a', 'field_b'],
  717. 'conditions' => ['field_a' => 1, 'field_b' => 'something'],
  718. 'limit' => 1,
  719. 'order' => ['a' => 'ASC'],
  720. 'offset' => 5,
  721. 'group' => ['field_a'],
  722. 'having' => ['field_a >' => 100],
  723. 'contain' => ['table_a' => ['table_b']],
  724. 'join' => ['table_a' => ['conditions' => ['a > b']]]
  725. ];
  726. $query = new Query($this->connection, $this->table);
  727. $query->applyOptions($options);
  728. $this->assertEquals(['field_a', 'field_b'], $query->clause('select'));
  729. $expected = new QueryExpression($options['conditions']);
  730. $result = $query->clause('where');
  731. $this->assertEquals($expected, $result);
  732. $this->assertEquals(1, $query->clause('limit'));
  733. $expected = new QueryExpression(['a > b']);
  734. $result = $query->clause('join');
  735. $this->assertEquals([
  736. 'table_a' => ['alias' => 'table_a', 'type' => 'INNER', 'conditions' => $expected]
  737. ], $result);
  738. $expected = new OrderByExpression(['a' => 'ASC']);
  739. $this->assertEquals($expected, $query->clause('order'));
  740. $this->assertEquals(5, $query->clause('offset'));
  741. $this->assertEquals(['field_a'], $query->clause('group'));
  742. $expected = new QueryExpression($options['having']);
  743. $this->assertEquals($expected, $query->clause('having'));
  744. $expected = ['table_a' => ['table_b' => []]];
  745. $this->assertEquals($expected, $query->contain());
  746. }
  747. /**
  748. * Test that page is applied after limit.
  749. *
  750. * @return void
  751. */
  752. public function testApplyOptionsPageIsLast() {
  753. $query = new Query($this->connection, $this->table);
  754. $opts = [
  755. 'page' => 3,
  756. 'limit' => 5
  757. ];
  758. $query->applyOptions($opts);
  759. $this->assertEquals(5, $query->clause('limit'));
  760. $this->assertEquals(10, $query->clause('offset'));
  761. }
  762. /**
  763. * ApplyOptions should ignore null values.
  764. *
  765. * @return void
  766. */
  767. public function testApplyOptionsIgnoreNull() {
  768. $options = [
  769. 'fields' => null,
  770. ];
  771. $query = new Query($this->connection, $this->table);
  772. $query->applyOptions($options);
  773. $this->assertEquals([], $query->clause('select'));
  774. }
  775. /**
  776. * Tests getOptions() method
  777. *
  778. * @return void
  779. */
  780. public function testGetOptions() {
  781. $options = ['doABarrelRoll' => true, 'fields' => ['id', 'name']];
  782. $query = new Query($this->connection, $this->table);
  783. $query->applyOptions($options);
  784. $expected = ['doABarrelRoll' => true];
  785. $this->assertEquals($expected, $query->getOptions());
  786. $expected = ['doABarrelRoll' => false, 'doAwesome' => true];
  787. $query->applyOptions($expected);
  788. $this->assertEquals($expected, $query->getOptions());
  789. }
  790. /**
  791. * Tests registering mappers with mapReduce()
  792. *
  793. * @return void
  794. */
  795. public function testMapReduceOnlyMapper() {
  796. $mapper1 = function() {
  797. };
  798. $mapper2 = function() {
  799. };
  800. $query = new Query($this->connection, $this->table);
  801. $this->assertSame($query, $query->mapReduce($mapper1));
  802. $this->assertEquals(
  803. [['mapper' => $mapper1, 'reducer' => null]],
  804. $query->mapReduce()
  805. );
  806. $this->assertEquals($query, $query->mapReduce($mapper2));
  807. $result = $query->mapReduce();
  808. $this->assertSame(
  809. [
  810. ['mapper' => $mapper1, 'reducer' => null],
  811. ['mapper' => $mapper2, 'reducer' => null]
  812. ],
  813. $result
  814. );
  815. }
  816. /**
  817. * Tests registering mappers and reducers with mapReduce()
  818. *
  819. * @return void
  820. */
  821. public function testMapReduceBothMethods() {
  822. $mapper1 = function() {
  823. };
  824. $mapper2 = function() {
  825. };
  826. $reducer1 = function() {
  827. };
  828. $reducer2 = function() {
  829. };
  830. $query = new Query($this->connection, $this->table);
  831. $this->assertSame($query, $query->mapReduce($mapper1, $reducer1));
  832. $this->assertEquals(
  833. [['mapper' => $mapper1, 'reducer' => $reducer1]],
  834. $query->mapReduce()
  835. );
  836. $this->assertSame($query, $query->mapReduce($mapper2, $reducer2));
  837. $this->assertEquals(
  838. [
  839. ['mapper' => $mapper1, 'reducer' => $reducer1],
  840. ['mapper' => $mapper2, 'reducer' => $reducer2]
  841. ],
  842. $query->mapReduce()
  843. );
  844. }
  845. /**
  846. * Tests that it is possible to overwrite previous map reducers
  847. *
  848. * @return void
  849. */
  850. public function testOverwriteMapReduce() {
  851. $mapper1 = function() {
  852. };
  853. $mapper2 = function() {
  854. };
  855. $reducer1 = function() {
  856. };
  857. $reducer2 = function() {
  858. };
  859. $query = new Query($this->connection, $this->table);
  860. $this->assertEquals($query, $query->mapReduce($mapper1, $reducer1));
  861. $this->assertEquals(
  862. [['mapper' => $mapper1, 'reducer' => $reducer1]],
  863. $query->mapReduce()
  864. );
  865. $this->assertEquals($query, $query->mapReduce($mapper2, $reducer2, true));
  866. $this->assertEquals(
  867. [['mapper' => $mapper2, 'reducer' => $reducer2]],
  868. $query->mapReduce()
  869. );
  870. }
  871. /**
  872. * Tests that multiple map reducers can be stacked
  873. *
  874. * @return void
  875. */
  876. public function testResultsAreWrappedInMapReduce() {
  877. $params = [$this->connection, $this->table];
  878. $query = $this->getMock('\Cake\ORM\Query', ['execute'], $params);
  879. $statement = $this->getMock(
  880. '\Database\StatementInterface',
  881. ['fetch', 'closeCursor', 'rowCount']
  882. );
  883. $statement->expects($this->exactly(3))
  884. ->method('fetch')
  885. ->will($this->onConsecutiveCalls(['a' => 1], ['a' => 2], false));
  886. $query->expects($this->once())
  887. ->method('execute')
  888. ->will($this->returnValue($statement));
  889. $query->mapReduce(function($v, $k, $mr) {
  890. $mr->emit($v['a']);
  891. });
  892. $query->mapReduce(
  893. function($v, $k, $mr) {
  894. $mr->emitIntermediate($v, $k);
  895. },
  896. function($v, $k, $mr) {
  897. $mr->emit($v[0] + 1);
  898. }
  899. );
  900. $this->assertEquals([2, 3], iterator_to_array($query->all()));
  901. }
  902. /**
  903. * Tests first() method when the query has not been executed before
  904. *
  905. * @return void
  906. */
  907. public function testFirstDirtyQuery() {
  908. $table = TableRegistry::get('articles', ['table' => 'articles']);
  909. $query = new Query($this->connection, $table);
  910. $result = $query->select(['id'])->hydrate(false)->first();
  911. $this->assertEquals(['id' => 1], $result);
  912. $this->assertEquals(1, $query->clause('limit'));
  913. $result = $query->select(['id'])->first();
  914. $this->assertEquals(['id' => 1], $result);
  915. }
  916. /**
  917. * Tests that first can be called again on an already executed query
  918. *
  919. * @return void
  920. */
  921. public function testFirstCleanQuery() {
  922. $table = TableRegistry::get('articles', ['table' => 'articles']);
  923. $query = new Query($this->connection, $table);
  924. $query->select(['id'])->toArray();
  925. $first = $query->hydrate(false)->first();
  926. $this->assertEquals(['id' => 1], $first);
  927. $this->assertEquals(1, $query->clause('limit'));
  928. }
  929. /**
  930. * Tests that first() will not execute the same query twice
  931. *
  932. * @return void
  933. */
  934. public function testFirstSameResult() {
  935. $table = TableRegistry::get('articles', ['table' => 'articles']);
  936. $query = new Query($this->connection, $table);
  937. $query->select(['id'])->toArray();
  938. $first = $query->hydrate(false)->first();
  939. $resultSet = $query->all();
  940. $this->assertEquals(['id' => 1], $first);
  941. $this->assertSame($resultSet, $query->all());
  942. }
  943. /**
  944. * Tests that first can be called against a query with a mapReduce
  945. *
  946. * @return void
  947. */
  948. public function testFirstMapReduce() {
  949. $map = function($row, $key, $mapReduce) {
  950. $mapReduce->emitIntermediate($row['id'], 'id');
  951. };
  952. $reduce = function($values, $key, $mapReduce) {
  953. $mapReduce->emit(array_sum($values));
  954. };
  955. $table = TableRegistry::get('articles', ['table' => 'articles']);
  956. $query = new Query($this->connection, $table);
  957. $query->select(['id'])
  958. ->hydrate(false)
  959. ->mapReduce($map, $reduce);
  960. $first = $query->first();
  961. $this->assertEquals(1, $first);
  962. }
  963. /**
  964. * Testing hydrating a result set into Entity objects
  965. *
  966. * @return void
  967. */
  968. public function testHydrateSimple() {
  969. $table = TableRegistry::get('articles', ['table' => 'articles']);
  970. $query = new Query($this->connection, $table);
  971. $results = $query->select()->toArray();
  972. $this->assertCount(3, $results);
  973. foreach ($results as $r) {
  974. $this->assertInstanceOf('\Cake\ORM\Entity', $r);
  975. }
  976. $first = $results[0];
  977. $this->assertEquals(1, $first->id);
  978. $this->assertEquals(1, $first->author_id);
  979. $this->assertEquals('First Article', $first->title);
  980. $this->assertEquals('First Article Body', $first->body);
  981. $this->assertEquals('Y', $first->published);
  982. }
  983. /**
  984. * Tests that has many results are also hydrated correctly
  985. *
  986. * @return void
  987. */
  988. public function testHydrateHasMany() {
  989. $table = TableRegistry::get('authors');
  990. TableRegistry::get('articles');
  991. $table->hasMany('articles', [
  992. 'propertyName' => 'articles',
  993. 'sort' => ['articles.id' => 'asc']
  994. ]);
  995. $query = new Query($this->connection, $table);
  996. $results = $query->select()
  997. ->contain('articles')
  998. ->toArray();
  999. $first = $results[0];
  1000. foreach ($first->articles as $r) {
  1001. $this->assertInstanceOf('\Cake\ORM\Entity', $r);
  1002. }
  1003. $this->assertCount(2, $first->articles);
  1004. $expected = [
  1005. 'id' => 1,
  1006. 'title' => 'First Article',
  1007. 'body' => 'First Article Body',
  1008. 'author_id' => 1,
  1009. 'published' => 'Y',
  1010. ];
  1011. $this->assertEquals($expected, $first->articles[0]->toArray());
  1012. $expected = [
  1013. 'id' => 3,
  1014. 'title' => 'Third Article',
  1015. 'author_id' => 1,
  1016. 'body' => 'Third Article Body',
  1017. 'published' => 'Y',
  1018. ];
  1019. $this->assertEquals($expected, $first->articles[1]->toArray());
  1020. }
  1021. /**
  1022. * Tests that belongsToMany associations are also correctly hydrated
  1023. *
  1024. * @return void
  1025. */
  1026. public function testHydrateBelongsToMany() {
  1027. $table = TableRegistry::get('Articles');
  1028. TableRegistry::get('Tags');
  1029. TableRegistry::get('ArticlesTags', [
  1030. 'table' => 'articles_tags'
  1031. ]);
  1032. $table->belongsToMany('Tags');
  1033. $query = new Query($this->connection, $table);
  1034. $results = $query
  1035. ->select()
  1036. ->contain('Tags')
  1037. ->toArray();
  1038. $first = $results[0];
  1039. foreach ($first->tags as $r) {
  1040. $this->assertInstanceOf('\Cake\ORM\Entity', $r);
  1041. }
  1042. $this->assertCount(2, $first->tags);
  1043. $expected = [
  1044. 'id' => 1,
  1045. 'name' => 'tag1',
  1046. '_joinData' => ['article_id' => 1, 'tag_id' => 1]
  1047. ];
  1048. $this->assertEquals($expected, $first->tags[0]->toArray());
  1049. $expected = [
  1050. 'id' => 2,
  1051. 'name' => 'tag2',
  1052. '_joinData' => ['article_id' => 1, 'tag_id' => 2]
  1053. ];
  1054. $this->assertEquals($expected, $first->tags[1]->toArray());
  1055. }
  1056. /**
  1057. * Tests that belongsTo relations are correctly hydrated
  1058. *
  1059. * @return void
  1060. */
  1061. public function testHydrateBelongsTo() {
  1062. $table = TableRegistry::get('articles');
  1063. TableRegistry::get('authors');
  1064. $table->belongsTo('authors');
  1065. $query = new Query($this->connection, $table);
  1066. $results = $query->select()
  1067. ->contain('authors')
  1068. ->order(['articles.id' => 'asc'])
  1069. ->toArray();
  1070. $this->assertCount(3, $results);
  1071. $first = $results[0];
  1072. $this->assertInstanceOf('\Cake\ORM\Entity', $first->author);
  1073. $expected = ['id' => 1, 'name' => 'mariano'];
  1074. $this->assertEquals($expected, $first->author->toArray());
  1075. }
  1076. /**
  1077. * Tests that deeply nested associations are also hydrated correctly
  1078. *
  1079. * @return void
  1080. */
  1081. public function testHydrateDeep() {
  1082. $table = TableRegistry::get('authors');
  1083. $article = TableRegistry::get('articles');
  1084. $table->hasMany('articles', [
  1085. 'propertyName' => 'articles',
  1086. 'sort' => ['articles.id' => 'asc']
  1087. ]);
  1088. $article->belongsTo('authors');
  1089. $query = new Query($this->connection, $table);
  1090. $results = $query->select()
  1091. ->contain(['articles' => ['authors']])
  1092. ->toArray();
  1093. $this->assertCount(4, $results);
  1094. $first = $results[0];
  1095. $this->assertInstanceOf('\Cake\ORM\Entity', $first->articles[0]->author);
  1096. $expected = ['id' => 1, 'name' => 'mariano'];
  1097. $this->assertEquals($expected, $first->articles[0]->author->toArray());
  1098. $this->assertFalse(isset($results[3]->articles));
  1099. }
  1100. /**
  1101. * Tests that it is possible to use a custom entity class
  1102. *
  1103. * @return void
  1104. */
  1105. public function testHydrateCustomObject() {
  1106. $class = $this->getMockClass('\Cake\ORM\Entity', ['fakeMethod']);
  1107. $table = TableRegistry::get('articles', [
  1108. 'table' => 'articles',
  1109. 'entityClass' => '\\' . $class
  1110. ]);
  1111. $query = new Query($this->connection, $table);
  1112. $results = $query->select()->toArray();
  1113. $this->assertCount(3, $results);
  1114. foreach ($results as $r) {
  1115. $this->assertInstanceOf($class, $r);
  1116. }
  1117. $first = $results[0];
  1118. $this->assertEquals(1, $first->id);
  1119. $this->assertEquals(1, $first->author_id);
  1120. $this->assertEquals('First Article', $first->title);
  1121. $this->assertEquals('First Article Body', $first->body);
  1122. $this->assertEquals('Y', $first->published);
  1123. }
  1124. /**
  1125. * Tests that has many results are also hydrated correctly
  1126. * when specified a custom entity class
  1127. *
  1128. * @return void
  1129. */
  1130. public function testHydrateHasManyCustomEntity() {
  1131. $authorEntity = $this->getMockClass('\Cake\ORM\Entity', ['foo']);
  1132. $articleEntity = $this->getMockClass('\Cake\ORM\Entity', ['foo']);
  1133. $table = TableRegistry::get('authors', [
  1134. 'entityClass' => '\\' . $authorEntity
  1135. ]);
  1136. TableRegistry::get('articles', [
  1137. 'entityClass' => '\\' . $articleEntity
  1138. ]);
  1139. $table->hasMany('articles', [
  1140. 'propertyName' => 'articles',
  1141. 'sort' => ['articles.id' => 'asc']
  1142. ]);
  1143. $query = new Query($this->connection, $table);
  1144. $results = $query->select()
  1145. ->contain('articles')
  1146. ->toArray();
  1147. $first = $results[0];
  1148. $this->assertInstanceOf($authorEntity, $first);
  1149. foreach ($first->articles as $r) {
  1150. $this->assertInstanceOf($articleEntity, $r);
  1151. }
  1152. $this->assertCount(2, $first->articles);
  1153. $expected = [
  1154. 'id' => 1,
  1155. 'title' => 'First Article',
  1156. 'body' => 'First Article Body',
  1157. 'author_id' => 1,
  1158. 'published' => 'Y',
  1159. ];
  1160. $this->assertEquals($expected, $first->articles[0]->toArray());
  1161. }
  1162. /**
  1163. * Tests that belongsTo relations are correctly hydrated into a custom entity class
  1164. *
  1165. * @return void
  1166. */
  1167. public function testHydrateBelongsToCustomEntity() {
  1168. $authorEntity = $this->getMockClass('\Cake\ORM\Entity', ['foo']);
  1169. $table = TableRegistry::get('articles');
  1170. TableRegistry::get('authors', [
  1171. 'entityClass' => '\\' . $authorEntity
  1172. ]);
  1173. $table->belongsTo('authors');
  1174. $query = new Query($this->connection, $table);
  1175. $results = $query->select()
  1176. ->contain('authors')
  1177. ->order(['articles.id' => 'asc'])
  1178. ->toArray();
  1179. $first = $results[0];
  1180. $this->assertInstanceOf($authorEntity, $first->author);
  1181. }
  1182. /**
  1183. * Test getting counts from queries.
  1184. *
  1185. * @return void
  1186. */
  1187. public function testCount() {
  1188. $table = TableRegistry::get('articles');
  1189. $result = $table->find('all')->count();
  1190. $this->assertSame(3, $result);
  1191. $query = $table->find('all')
  1192. ->where(['id >' => 1])
  1193. ->limit(1);
  1194. $result = $query->count();
  1195. $this->assertSame(2, $result);
  1196. $result = $query->all();
  1197. $this->assertCount(1, $result);
  1198. $this->assertEquals(2, $result->first()->id);
  1199. }
  1200. /**
  1201. * Test that count() returns correct results with group by.
  1202. *
  1203. * @return void
  1204. */
  1205. public function testCountWithGroup() {
  1206. $table = TableRegistry::get('articles');
  1207. $query = $table->find('all');
  1208. $query->select(['author_id', 's' => $query->func()->sum('id')])
  1209. ->group(['author_id']);
  1210. $result = $query->count();
  1211. $this->assertEquals(2, $result);
  1212. }
  1213. /**
  1214. * Tests that it is possible to provide a callback for calculating the count
  1215. * of a query
  1216. *
  1217. * @return void
  1218. */
  1219. public function testCountWithCustomCounter() {
  1220. $table = TableRegistry::get('articles');
  1221. $query = $table->find('all');
  1222. $query
  1223. ->select(['author_id', 's' => $query->func()->sum('id')])
  1224. ->where(['id >' => 2])
  1225. ->group(['author_id'])
  1226. ->counter(function($q) use ($query) {
  1227. $this->assertNotSame($q, $query);
  1228. return $q->select([], true)->group([], true)->count();
  1229. });
  1230. $result = $query->count();
  1231. $this->assertEquals(1, $result);
  1232. }
  1233. /**
  1234. * Test update method.
  1235. *
  1236. * @return void
  1237. */
  1238. public function testUpdate() {
  1239. $table = TableRegistry::get('articles');
  1240. $result = $table->query()
  1241. ->update()
  1242. ->set(['title' => 'First'])
  1243. ->execute();
  1244. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1245. $this->assertTrue($result->rowCount() > 0);
  1246. }
  1247. /**
  1248. * Test insert method.
  1249. *
  1250. * @return void
  1251. */
  1252. public function testInsert() {
  1253. $table = TableRegistry::get('articles');
  1254. $result = $table->query()
  1255. ->insert(['title'])
  1256. ->values(['title' => 'First'])
  1257. ->values(['title' => 'Second'])
  1258. ->execute();
  1259. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1260. $this->assertEquals(2, $result->rowCount());
  1261. }
  1262. /**
  1263. * Test delete method.
  1264. *
  1265. * @return void
  1266. */
  1267. public function testDelete() {
  1268. $table = TableRegistry::get('articles');
  1269. $result = $table->query()
  1270. ->delete()
  1271. ->where(['id >=' => 1])
  1272. ->execute();
  1273. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1274. $this->assertTrue($result->rowCount() > 0);
  1275. }
  1276. /**
  1277. * Provides a list of collection methods that can be proxied
  1278. * from the query
  1279. *
  1280. * @return array
  1281. */
  1282. public function collectionMethodsProvider() {
  1283. $identity = function($a) {
  1284. return $a;
  1285. };
  1286. return [
  1287. ['filter', $identity],
  1288. ['reject', $identity],
  1289. ['every', $identity],
  1290. ['some', $identity],
  1291. ['contains', $identity],
  1292. ['map', $identity],
  1293. ['reduce', $identity],
  1294. ['extract', $identity],
  1295. ['max', $identity],
  1296. ['min', $identity],
  1297. ['sortBy', $identity],
  1298. ['groupBy', $identity],
  1299. ['countBy', $identity],
  1300. ['shuffle', $identity],
  1301. ['sample', $identity],
  1302. ['take', 1],
  1303. ['append', new \ArrayIterator],
  1304. ['compile', 1],
  1305. ];
  1306. }
  1307. /**
  1308. * Tests that query can proxy collection methods
  1309. *
  1310. * @dataProvider collectionMethodsProvider
  1311. * @return void
  1312. */
  1313. public function testCollectionProxy($method, $arg) {
  1314. $query = $this->getMock(
  1315. '\Cake\ORM\Query', ['all'],
  1316. [$this->connection, $this->table]
  1317. );
  1318. $query->select();
  1319. $resultSet = $this->getMock('\Cake\ORM\ResultSet', [], [$query, null]);
  1320. $query->expects($this->once())
  1321. ->method('all')
  1322. ->will($this->returnValue($resultSet));
  1323. $resultSet->expects($this->once())
  1324. ->method($method)
  1325. ->with($arg, 'extra')
  1326. ->will($this->returnValue(new \Cake\Collection\Collection([])));
  1327. $this->assertInstanceOf(
  1328. '\Cake\Collection\Collection',
  1329. $query->{$method}($arg, 'extra')
  1330. );
  1331. }
  1332. /**
  1333. * Tests that calling an inexistent method in query throws an
  1334. * exception
  1335. *
  1336. * @expectedException \BadMethodCallException
  1337. * @expectedExceptionMessage Unknown method "derpFilter"
  1338. * @return void
  1339. */
  1340. public function testCollectionProxyBadMethod() {
  1341. TableRegistry::get('articles')->find('all')->derpFilter();
  1342. }
  1343. /**
  1344. * cache() should fail on non select queries.
  1345. *
  1346. * @expectedException RuntimeException
  1347. * @return void
  1348. */
  1349. public function testCacheErrorOnNonSelect() {
  1350. $table = TableRegistry::get('articles', ['table' => 'articles']);
  1351. $query = new Query($this->connection, $table);
  1352. $query->insert(['test']);
  1353. $query->cache('my_key');
  1354. }
  1355. /**
  1356. * Integration test for query caching.
  1357. *
  1358. * @return void
  1359. */
  1360. public function testCacheReadIntegration() {
  1361. $query = $this->getMock(
  1362. '\Cake\ORM\Query', ['execute'],
  1363. [$this->connection, $this->table]
  1364. );
  1365. $resultSet = $this->getMock('\Cake\ORM\ResultSet', [], [$query, null]);
  1366. $query->expects($this->never())
  1367. ->method('execute');
  1368. $cacher = $this->getMock('Cake\Cache\CacheEngine');
  1369. $cacher->expects($this->once())
  1370. ->method('read')
  1371. ->with('my_key')
  1372. ->will($this->returnValue($resultSet));
  1373. $query->cache('my_key', $cacher)
  1374. ->where(['id' => 1]);
  1375. $results = $query->all();
  1376. $this->assertSame($resultSet, $results);
  1377. }
  1378. /**
  1379. * Integration test for query caching.
  1380. *
  1381. * @return void
  1382. */
  1383. public function testCacheWriteIntegration() {
  1384. $table = TableRegistry::get('Articles');
  1385. $query = new Query($this->connection, $table);
  1386. $query->select(['id', 'title']);
  1387. $cacher = $this->getMock('Cake\Cache\CacheEngine');
  1388. $cacher->expects($this->once())
  1389. ->method('write')
  1390. ->with(
  1391. 'my_key',
  1392. $this->isInstanceOf('Cake\ORM\ResultSet')
  1393. );
  1394. $query->cache('my_key', $cacher)
  1395. ->where(['id' => 1]);
  1396. $query->all();
  1397. }
  1398. /**
  1399. * Integration test to show filtering associations using contain and a closure
  1400. *
  1401. * @return void
  1402. */
  1403. public function testContainWithClosure() {
  1404. $table = TableRegistry::get('authors');
  1405. $table->hasMany('articles');
  1406. $query = new Query($this->connection, $table);
  1407. $query
  1408. ->select()
  1409. ->contain(['articles' => function($q) {
  1410. return $q->where(['articles.id' => 1]);
  1411. }]);
  1412. $ids = [];
  1413. foreach ($query as $entity) {
  1414. foreach ((array)$entity->articles as $article) {
  1415. $ids[] = $article->id;
  1416. }
  1417. }
  1418. $this->assertEquals([1], array_unique($ids));
  1419. }
  1420. /**
  1421. * Tests the formatResults method
  1422. *
  1423. * @return void
  1424. */
  1425. public function testFormatResults() {
  1426. $callback1 = function() {
  1427. };
  1428. $callback2 = function() {
  1429. };
  1430. $table = TableRegistry::get('authors');
  1431. $query = new Query($this->connection, $table);
  1432. $this->assertSame($query, $query->formatResults($callback1));
  1433. $this->assertSame([$callback1], $query->formatResults());
  1434. $this->assertSame($query, $query->formatResults($callback2));
  1435. $this->assertSame([$callback1, $callback2], $query->formatResults());
  1436. $query->formatResults($callback2, true);
  1437. $this->assertSame([$callback2], $query->formatResults());
  1438. $query->formatResults(null, true);
  1439. $this->assertSame([], $query->formatResults());
  1440. $query->formatResults($callback1);
  1441. $query->formatResults($callback2, $query::PREPEND);
  1442. $this->assertSame([$callback2, $callback1], $query->formatResults());
  1443. }
  1444. /**
  1445. * Test fetching results from a qurey with a custom formatter
  1446. *
  1447. * @return void
  1448. */
  1449. public function testQueryWithFormatter() {
  1450. $table = TableRegistry::get('authors');
  1451. $query = new Query($this->connection, $table);
  1452. $query->select()->formatResults(function($results, $q) use ($query) {
  1453. $this->assertSame($query, $q);
  1454. $this->assertInstanceOf('\Cake\ORM\ResultSet', $results);
  1455. return $results->indexBy('id');
  1456. });
  1457. $this->assertEquals([1, 2, 3, 4], array_keys($query->toArray()));
  1458. }
  1459. /**
  1460. * Test fetching results from a qurey with a two custom formatters
  1461. *
  1462. * @return void
  1463. */
  1464. public function testQueryWithStackedFormatters() {
  1465. $table = TableRegistry::get('authors');
  1466. $query = new Query($this->connection, $table);
  1467. $query->select()->formatResults(function($results, $q) use ($query) {
  1468. $this->assertSame($query, $q);
  1469. $this->assertInstanceOf('\Cake\ORM\ResultSet', $results);
  1470. return $results->indexBy('id');
  1471. });
  1472. $query->formatResults(function($results) {
  1473. return $results->extract('name');
  1474. });
  1475. $expected = [
  1476. 1 => 'mariano',
  1477. 2 => 'nate',
  1478. 3 => 'larry',
  1479. 4 => 'garrett'
  1480. ];
  1481. $this->assertEquals($expected, $query->toArray());
  1482. }
  1483. /**
  1484. * Tests that getting results from a query having a contained association
  1485. * will no attach joins twice if count() is called on it afterwards
  1486. *
  1487. * @return void
  1488. */
  1489. public function testCountWithContainCallingAll() {
  1490. $table = TableRegistry::get('articles');
  1491. $table->belongsTo('authors');
  1492. $query = $table->find()
  1493. ->select(['id', 'title'])
  1494. ->contain('authors')
  1495. ->limit(2);
  1496. $results = $query->all();
  1497. $this->assertCount(2, $results);
  1498. $this->assertEquals(3, $query->count());
  1499. }
  1500. /**
  1501. * Tests that it is possible to apply formatters inside the query builder
  1502. * for belongsTo associations
  1503. *
  1504. * @return void
  1505. */
  1506. public function testFormatBelongsToRecords() {
  1507. $table = TableRegistry::get('articles');
  1508. $table->belongsTo('authors');
  1509. $query = $table->find()
  1510. ->contain(['authors' => function($q) {
  1511. return $q
  1512. ->formatResults(function($authors) {
  1513. return $authors->map(function($author) {
  1514. $author->idCopy = $author->id;
  1515. return $author;
  1516. });
  1517. })
  1518. ->formatResults(function($authors) {
  1519. return $authors->map(function($author) {
  1520. $author->idCopy = $author->idCopy + 2;
  1521. return $author;
  1522. });
  1523. });
  1524. }]);
  1525. $query->formatResults(function($results) {
  1526. return $results->combine('id', 'author.idCopy');
  1527. });
  1528. $results = $query->toArray();
  1529. $expected = [1 => 3, 2 => 5, 3 => 3];
  1530. $this->assertEquals($expected, $results);
  1531. }
  1532. /**
  1533. * Tests it is possible to apply formatters to deep relations.
  1534. *
  1535. * @return void
  1536. */
  1537. public function testFormatDeepAssocationRecords() {
  1538. $table = TableRegistry::get('ArticlesTags');
  1539. $table->belongsTo('Articles');
  1540. $table->association('Articles')->target()->belongsTo('Authors');
  1541. $builder = function($q) {
  1542. return $q
  1543. ->formatResults(function($results) {
  1544. return $results->map(function($result) {
  1545. $result->idCopy = $result->id;
  1546. return $result;
  1547. });
  1548. })
  1549. ->formatResults(function($results) {
  1550. return $results->map(function($result) {
  1551. $result->idCopy = $result->idCopy + 2;
  1552. return $result;
  1553. });
  1554. });
  1555. };
  1556. $query = $table->find()
  1557. ->contain(['Articles' => $builder, 'Articles.Authors' => $builder]);
  1558. $query->formatResults(function($results) {
  1559. return $results->map(function($row) {
  1560. return sprintf(
  1561. '%s - %s - %s',
  1562. $row->tag_id,
  1563. $row->article->idCopy,
  1564. $row->article->author->idCopy
  1565. );
  1566. });
  1567. });
  1568. $expected = ['1 - 3 - 3', '2 - 3 - 3', '1 - 4 - 5', '3 - 4 - 5'];
  1569. $this->assertEquals($expected, $query->toArray());
  1570. }
  1571. /**
  1572. * Tests that formatters cna be applied to deep associaitons that are fetched using
  1573. * additional queries
  1574. *
  1575. * @return void
  1576. */
  1577. public function testFormatDeepDistantAssociationRecords() {
  1578. $table = TableRegistry::get('authors');
  1579. $table->hasMany('articles');
  1580. $articles = $table->association('articles')->target();
  1581. $articles->hasMany('articlesTags');
  1582. $articles->association('articlesTags')->target()->belongsTo('tags');
  1583. $query = $table->find()->contain(['articles.articlesTags.tags' => function($q) {
  1584. return $q->formatResults(function($results) {
  1585. return $results->map(function($tag) {
  1586. $tag->name .= ' - visited';
  1587. return $tag;
  1588. });
  1589. });
  1590. }]);
  1591. $query->mapReduce(function($row, $key, $mr) {
  1592. foreach ((array)$row->articles as $article) {
  1593. foreach ((array)$article->articles_tags as $articleTag) {
  1594. $mr->emit($articleTag->tag->name);
  1595. }
  1596. }
  1597. });
  1598. $expected = ['tag1 - visited', 'tag2 - visited', 'tag1 - visited', 'tag3 - visited'];
  1599. $this->assertEquals($expected, $query->toArray());
  1600. }
  1601. /**
  1602. * Tests that it is possible to attach more association when using a query
  1603. * builder for other associaitons
  1604. *
  1605. * @return void
  1606. */
  1607. public function testContainInAssociationQuery() {
  1608. $table = TableRegistry::get('ArticlesTags');
  1609. $table->belongsTo('Articles');
  1610. $table->association('Articles')->target()->belongsTo('Authors');
  1611. $query = $table->find()->contain(['Articles' => function($q) {
  1612. return $q->contain('Authors');
  1613. }]);
  1614. $results = $query->extract('article.author.name')->toArray();
  1615. $expected = ['mariano', 'mariano', 'larry', 'larry'];
  1616. $this->assertEquals($expected, $results);
  1617. }
  1618. /**
  1619. * Tests that it is possible to apply more `matching` conditions inside query
  1620. * builders for associations
  1621. *
  1622. * @return void
  1623. */
  1624. public function testContainInAssociationMatching() {
  1625. $table = TableRegistry::get('authors');
  1626. $table->hasMany('articles');
  1627. $articles = $table->association('articles')->target();
  1628. $articles->hasMany('articlesTags');
  1629. $articles->association('articlesTags')->target()->belongsTo('tags');
  1630. $query = $table->find()->matching('articles.articlesTags', function($q) {
  1631. return $q->matching('tags', function($q) {
  1632. return $q->where(['tags.name' => 'tag3']);
  1633. });
  1634. });
  1635. $results = $query->toArray();
  1636. $this->assertCount(1, $results);
  1637. $this->assertEquals('tag3', $results[0]->articles->articles_tags->tag->name);
  1638. }
  1639. /**
  1640. * Tests __debugInfo
  1641. *
  1642. * @return void
  1643. */
  1644. public function testDebugInfo() {
  1645. $table = TableRegistry::get('authors');
  1646. $table->hasMany('articles');
  1647. $query = $table->find()
  1648. ->where(['id > ' => 1])
  1649. ->bufferResults(false)
  1650. ->hydrate(false)
  1651. ->matching('articles')
  1652. ->applyOptions(['foo' => 'bar'])
  1653. ->formatResults(function($results) {
  1654. return $results;
  1655. })
  1656. ->mapReduce(function($item, $key, $mr) {
  1657. $mr->emit($item);
  1658. });
  1659. $expected = [
  1660. 'sql' => $query->sql(),
  1661. 'params' => $query->valueBinder()->bindings(),
  1662. 'defaultTypes' => [
  1663. 'authors.id' => 'integer',
  1664. 'id' => 'integer',
  1665. 'authors.name' => 'string',
  1666. 'name' => 'string'
  1667. ],
  1668. 'decorators' => 0,
  1669. 'executed' => false,
  1670. 'hydrate' => false,
  1671. 'buffered' => false,
  1672. 'formatters' => 1,
  1673. 'mapReducers' => 1,
  1674. 'contain' => [
  1675. 'articles' => [
  1676. 'queryBuilder' => null,
  1677. 'matching' => true
  1678. ]
  1679. ],
  1680. 'extraOptions' => ['foo' => 'bar'],
  1681. 'repository' => $table
  1682. ];
  1683. $this->assertSame($expected, $query->__debugInfo());
  1684. }
  1685. /**
  1686. * Tests that the eagerLoaded function works and is transmitted correctly to eagerly
  1687. * loaded associations
  1688. *
  1689. * @return void
  1690. */
  1691. public function testEagerLoaded() {
  1692. $table = TableRegistry::get('authors');
  1693. $table->hasMany('articles');
  1694. $query = $table->find()->contain(['articles' => function($q) {
  1695. $this->assertTrue($q->eagerLoaded());
  1696. return $q;
  1697. }]);
  1698. $this->assertFalse($query->eagerLoaded());
  1699. $table->getEventManager()->attach(function($e, $q, $o, $primary) {
  1700. $this->assertTrue($primary);
  1701. }, 'Model.beforeFind');
  1702. TableRegistry::get('articles')
  1703. ->getEventManager()->attach(function($e, $q, $o, $primary) {
  1704. $this->assertFalse($primary);
  1705. }, 'Model.beforeFind');
  1706. $query->all();
  1707. }
  1708. /**
  1709. * Tests that columns from manual joins are also contained in the result set
  1710. *
  1711. * @return void
  1712. */
  1713. public function testColumnsFromJoin() {
  1714. $table = TableRegistry::get('articles');
  1715. $results = $table->find()
  1716. ->select(['title', 'person.name'])
  1717. ->join([
  1718. 'person' => [
  1719. 'table' => 'authors',
  1720. 'conditions' => ['person.id = articles.author_id']
  1721. ]
  1722. ])
  1723. ->order(['articles.id' => 'ASC'])
  1724. ->hydrate(false)
  1725. ->toArray();
  1726. $expected = [
  1727. ['title' => 'First Article', 'person' => ['name' => 'mariano']],
  1728. ['title' => 'Second Article', 'person' => ['name' => 'larry']],
  1729. ['title' => 'Third Article', 'person' => ['name' => 'mariano']],
  1730. ];
  1731. $this->assertSame($expected, $results);
  1732. }
  1733. /**
  1734. * Tests that it is possible to use the same association aliases in the association
  1735. * chain for contain
  1736. *
  1737. * @return void
  1738. */
  1739. public function testRepeatedAssociationAliases() {
  1740. $table = TableRegistry::get('ArticlesTags');
  1741. $table->belongsTo('Articles');
  1742. $table->belongsTo('Tags');
  1743. TableRegistry::get('Tags')->belongsToMany('Articles');
  1744. $results = $table->find()->contain(['Articles', 'Tags.Articles'])->hydrate(false)->toArray();
  1745. $this->assertNotEmpty($results[0]['tag']['articles']);
  1746. $this->assertNotEmpty($results[0]['article']);
  1747. $this->assertNotEmpty($results[1]['tag']['articles']);
  1748. $this->assertNotEmpty($results[1]['article']);
  1749. $this->assertNotEmpty($results[2]['tag']['articles']);
  1750. $this->assertNotEmpty($results[2]['article']);
  1751. }
  1752. }