QueryTest.php 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619
  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 CakePHP(tm) v 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\ConnectionManager;
  17. use Cake\Database\Expression\IdentifierExpression;
  18. use Cake\Database\Expression\OrderByExpression;
  19. use Cake\Database\Expression\QueryExpression;
  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. 'property' => '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 set fields & order in a hasMany result set
  229. *
  230. * @dataProvider strategiesProvider
  231. * @return void
  232. **/
  233. public function testHasManyEagerLoadingFieldsAndOrderNoHydration($strategy) {
  234. $table = TableRegistry::get('authors');
  235. TableRegistry::get('articles');
  236. $table->hasMany('articles', ['property' => 'articles'] + compact('strategy'));
  237. $query = new Query($this->connection, $table);
  238. $results = $query->select()
  239. ->contain([
  240. 'articles' => [
  241. 'fields' => ['title', 'author_id'],
  242. 'sort' => ['id' => 'DESC']
  243. ]
  244. ])
  245. ->hydrate(false)
  246. ->toArray();
  247. $expected = [
  248. [
  249. 'id' => 1,
  250. 'name' => 'mariano',
  251. 'articles' => [
  252. ['title' => 'Third Article', 'author_id' => 1],
  253. ['title' => 'First Article', 'author_id' => 1],
  254. ]
  255. ],
  256. [
  257. 'id' => 2,
  258. 'name' => 'nate',
  259. ],
  260. [
  261. 'id' => 3,
  262. 'name' => 'larry',
  263. 'articles' => [
  264. ['title' => 'Second Article', 'author_id' => 3],
  265. ]
  266. ],
  267. [
  268. 'id' => 4,
  269. 'name' => 'garrett',
  270. ],
  271. ];
  272. $this->assertEquals($expected, $results);
  273. }
  274. /**
  275. * Tests that deep associations can be eagerly loaded
  276. *
  277. * @dataProvider strategiesProvider
  278. * @return void
  279. */
  280. public function testHasManyEagerLoadingDeep($strategy) {
  281. $table = TableRegistry::get('authors');
  282. $article = TableRegistry::get('articles');
  283. $table->hasMany('articles', [
  284. 'property' => 'articles',
  285. 'stratgey' => $strategy,
  286. 'sort' => ['articles.id' => 'asc']
  287. ]);
  288. $article->belongsTo('authors');
  289. $query = new Query($this->connection, $table);
  290. $results = $query->select()
  291. ->contain(['articles' => ['authors']])
  292. ->hydrate(false)
  293. ->toArray();
  294. $expected = [
  295. [
  296. 'id' => 1,
  297. 'name' => 'mariano',
  298. 'articles' => [
  299. [
  300. 'id' => 1,
  301. 'title' => 'First Article',
  302. 'author_id' => 1,
  303. 'body' => 'First Article Body',
  304. 'published' => 'Y',
  305. 'author' => ['id' => 1, 'name' => 'mariano']
  306. ],
  307. [
  308. 'id' => 3,
  309. 'title' => 'Third Article',
  310. 'author_id' => 1,
  311. 'body' => 'Third Article Body',
  312. 'published' => 'Y',
  313. 'author' => ['id' => 1, 'name' => 'mariano']
  314. ],
  315. ]
  316. ],
  317. [
  318. 'id' => 2,
  319. 'name' => 'nate'
  320. ],
  321. [
  322. 'id' => 3,
  323. 'name' => 'larry',
  324. 'articles' => [
  325. [
  326. 'id' => 2,
  327. 'title' => 'Second Article',
  328. 'author_id' => 3,
  329. 'body' => 'Second Article Body',
  330. 'published' => 'Y',
  331. 'author' => ['id' => 3, 'name' => 'larry']
  332. ],
  333. ]
  334. ],
  335. [
  336. 'id' => 4,
  337. 'name' => 'garrett'
  338. ]
  339. ];
  340. $this->assertEquals($expected, $results);
  341. }
  342. /**
  343. * Tests that hasMany associations can be loaded even when related to a secondary
  344. * model in the query
  345. *
  346. * @dataProvider strategiesProvider
  347. * @return void
  348. */
  349. public function testHasManyEagerLoadingFromSecondaryTable($strategy) {
  350. $author = TableRegistry::get('authors');
  351. $article = TableRegistry::get('articles');
  352. $post = TableRegistry::get('posts');
  353. $author->hasMany('posts', compact('strategy'));
  354. $article->belongsTo('authors');
  355. $query = new Query($this->connection, $article);
  356. $results = $query->select()
  357. ->contain(['authors' => ['posts']])
  358. ->order(['articles.id' => 'ASC'])
  359. ->hydrate(false)
  360. ->toArray();
  361. $expected = [
  362. [
  363. 'id' => 1,
  364. 'title' => 'First Article',
  365. 'body' => 'First Article Body',
  366. 'author_id' => 1,
  367. 'published' => 'Y',
  368. 'author' => [
  369. 'id' => 1,
  370. 'name' => 'mariano',
  371. 'posts' => [
  372. [
  373. 'id' => '1',
  374. 'title' => 'First Post',
  375. 'body' => 'First Post Body',
  376. 'author_id' => 1,
  377. 'published' => 'Y',
  378. ],
  379. [
  380. 'id' => '3',
  381. 'title' => 'Third Post',
  382. 'body' => 'Third Post Body',
  383. 'author_id' => 1,
  384. 'published' => 'Y',
  385. ],
  386. ]
  387. ]
  388. ],
  389. [
  390. 'id' => 2,
  391. 'title' => 'Second Article',
  392. 'body' => 'Second Article Body',
  393. 'author_id' => 3,
  394. 'published' => 'Y',
  395. 'author' => [
  396. 'id' => 3,
  397. 'name' => 'larry',
  398. 'posts' => [
  399. [
  400. 'id' => 2,
  401. 'title' => 'Second Post',
  402. 'body' => 'Second Post Body',
  403. 'author_id' => 3,
  404. 'published' => 'Y',
  405. ]
  406. ]
  407. ]
  408. ],
  409. [
  410. 'id' => 3,
  411. 'title' => 'Third Article',
  412. 'body' => 'Third Article Body',
  413. 'author_id' => 1,
  414. 'published' => 'Y',
  415. 'author' => [
  416. 'id' => 1,
  417. 'name' => 'mariano',
  418. 'posts' => [
  419. [
  420. 'id' => '1',
  421. 'title' => 'First Post',
  422. 'body' => 'First Post Body',
  423. 'author_id' => 1,
  424. 'published' => 'Y',
  425. ],
  426. [
  427. 'id' => '3',
  428. 'title' => 'Third Post',
  429. 'body' => 'Third Post Body',
  430. 'author_id' => 1,
  431. 'published' => 'Y',
  432. ],
  433. ]
  434. ]
  435. ],
  436. ];
  437. $this->assertEquals($expected, $results);
  438. }
  439. /**
  440. * Tests that BelongsToMany associations are correctly eager loaded.
  441. * Also that the query object passes the correct parent model keys to the
  442. * association objects in order to perform eager loading with select strategy
  443. *
  444. * @dataProvider strategiesProvider
  445. * @return void
  446. **/
  447. public function testBelongsToManyEagerLoadingNoHydration($strategy) {
  448. $table = TableRegistry::get('Articles');
  449. TableRegistry::get('Tags');
  450. TableRegistry::get('ArticlesTags', [
  451. 'table' => 'articles_tags'
  452. ]);
  453. $table->belongsToMany('Tags', ['strategy' => $strategy]);
  454. $query = new Query($this->connection, $table);
  455. $results = $query->select()->contain('Tags')->hydrate(false)->toArray();
  456. $expected = [
  457. [
  458. 'id' => 1,
  459. 'author_id' => 1,
  460. 'title' => 'First Article',
  461. 'body' => 'First Article Body',
  462. 'published' => 'Y',
  463. 'tags' => [
  464. [
  465. 'id' => 1,
  466. 'name' => 'tag1',
  467. '_joinData' => ['article_id' => 1, 'tag_id' => 1]
  468. ],
  469. [
  470. 'id' => 2,
  471. 'name' => 'tag2',
  472. '_joinData' => ['article_id' => 1, 'tag_id' => 2]
  473. ]
  474. ]
  475. ],
  476. [
  477. 'id' => 2,
  478. 'title' => 'Second Article',
  479. 'body' => 'Second Article Body',
  480. 'author_id' => 3,
  481. 'published' => 'Y',
  482. 'tags' => [
  483. [
  484. 'id' => 1,
  485. 'name' => 'tag1',
  486. '_joinData' => ['article_id' => 2, 'tag_id' => 1]
  487. ],
  488. [
  489. 'id' => 3,
  490. 'name' => 'tag3',
  491. '_joinData' => ['article_id' => 2, 'tag_id' => 3]
  492. ]
  493. ]
  494. ],
  495. [
  496. 'id' => 3,
  497. 'title' => 'Third Article',
  498. 'body' => 'Third Article Body',
  499. 'author_id' => 1,
  500. 'published' => 'Y',
  501. ],
  502. ];
  503. $this->assertEquals($expected, $results);
  504. $results = $query->select()
  505. ->contain(['Tags' => ['conditions' => ['id' => 3]]])
  506. ->hydrate(false)
  507. ->toArray();
  508. $expected = [
  509. [
  510. 'id' => 1,
  511. 'author_id' => 1,
  512. 'title' => 'First Article',
  513. 'body' => 'First Article Body',
  514. 'published' => 'Y',
  515. ],
  516. [
  517. 'id' => 2,
  518. 'title' => 'Second Article',
  519. 'body' => 'Second Article Body',
  520. 'author_id' => 3,
  521. 'published' => 'Y',
  522. 'tags' => [
  523. [
  524. 'id' => 3,
  525. 'name' => 'tag3',
  526. '_joinData' => ['article_id' => 2, 'tag_id' => 3]
  527. ]
  528. ]
  529. ],
  530. [
  531. 'id' => 3,
  532. 'title' => 'Third Article',
  533. 'body' => 'Third Article Body',
  534. 'author_id' => 1,
  535. 'published' => 'Y',
  536. ],
  537. ];
  538. $this->assertEquals($expected, $results);
  539. $this->assertEquals($table->association('Tags')->strategy(), $strategy);
  540. }
  541. /**
  542. * Tests that tables results can be filtered by the result of a HasMany
  543. *
  544. * @return void
  545. */
  546. public function testFilteringByHasManyNoHydration() {
  547. $query = new Query($this->connection, $this->table);
  548. $table = TableRegistry::get('authors');
  549. TableRegistry::get('articles');
  550. $table->hasMany('articles');
  551. $results = $query->repository($table)
  552. ->select()
  553. ->hydrate(false)
  554. ->matching('articles', function($q) {
  555. return $q->where(['articles.id' => 2]);
  556. })
  557. ->toArray();
  558. $expected = [
  559. [
  560. 'id' => 3,
  561. 'name' => 'larry',
  562. 'articles' => [
  563. 'id' => 2,
  564. 'title' => 'Second Article',
  565. 'body' => 'Second Article Body',
  566. 'author_id' => 3,
  567. 'published' => 'Y',
  568. ]
  569. ]
  570. ];
  571. $this->assertEquals($expected, $results);
  572. }
  573. /**
  574. * Tests that BelongsToMany associations are correctly eager loaded.
  575. * Also that the query object passes the correct parent model keys to the
  576. * association objects in order to perform eager loading with select strategy
  577. *
  578. * @return void
  579. **/
  580. public function testFilteringByBelongsToManyNoHydration() {
  581. $query = new Query($this->connection, $this->table);
  582. $table = TableRegistry::get('Articles');
  583. TableRegistry::get('Tags');
  584. TableRegistry::get('ArticlesTags', [
  585. 'table' => 'articles_tags'
  586. ]);
  587. $table->belongsToMany('Tags');
  588. $results = $query->repository($table)->select()
  589. ->matching('Tags', function($q) {
  590. return $q->where(['Tags.id' => 3]);
  591. })
  592. ->hydrate(false)
  593. ->toArray();
  594. $expected = [
  595. [
  596. 'id' => 2,
  597. 'author_id' => 3,
  598. 'title' => 'Second Article',
  599. 'body' => 'Second Article Body',
  600. 'published' => 'Y',
  601. 'tags' => [
  602. 'id' => 3,
  603. 'name' => 'tag3'
  604. ]
  605. ]
  606. ];
  607. $this->assertEquals($expected, $results);
  608. $query = new Query($this->connection, $table);
  609. $results = $query->select()
  610. ->matching('Tags', function($q) {
  611. return $q->where(['Tags.name' => 'tag2']);
  612. })
  613. ->hydrate(false)
  614. ->toArray();
  615. $expected = [
  616. [
  617. 'id' => 1,
  618. 'title' => 'First Article',
  619. 'body' => 'First Article Body',
  620. 'author_id' => 1,
  621. 'published' => 'Y',
  622. 'tags' => [
  623. 'id' => 2,
  624. 'name' => 'tag2'
  625. ]
  626. ]
  627. ];
  628. $this->assertEquals($expected, $results);
  629. }
  630. /**
  631. * Tests that it is possible to filter by deep associations
  632. *
  633. * @return void
  634. */
  635. public function testMatchingDotNotation() {
  636. $query = new Query($this->connection, $this->table);
  637. $table = TableRegistry::get('authors');
  638. TableRegistry::get('articles');
  639. $table->hasMany('articles');
  640. TableRegistry::get('articles')->belongsToMany('tags');
  641. $results = $query->repository($table)
  642. ->select()
  643. ->hydrate(false)
  644. ->matching('articles.tags', function($q) {
  645. return $q->where(['tags.id' => 2]);
  646. })
  647. ->toArray();
  648. $expected = [
  649. [
  650. 'id' => 1,
  651. 'name' => 'mariano',
  652. 'articles' => [
  653. 'id' => 1,
  654. 'title' => 'First Article',
  655. 'body' => 'First Article Body',
  656. 'author_id' => 1,
  657. 'published' => 'Y',
  658. 'tags' => [
  659. 'id' => 2,
  660. 'name' => 'tag2'
  661. ]
  662. ]
  663. ]
  664. ];
  665. $this->assertEquals($expected, $results);
  666. }
  667. /**
  668. * Test setResult()
  669. *
  670. * @return void
  671. */
  672. public function testSetResult() {
  673. $query = new Query($this->connection, $this->table);
  674. $stmt = $this->getMock('Cake\Database\StatementInterface');
  675. $results = new ResultSet($query, $stmt);
  676. $query->setResult($results);
  677. $this->assertSame($results, $query->all());
  678. }
  679. /**
  680. * Tests that applying array options to a query will convert them
  681. * to equivalent function calls with the correspondent array values
  682. *
  683. * @return void
  684. */
  685. public function testApplyOptions() {
  686. $options = [
  687. 'fields' => ['field_a', 'field_b'],
  688. 'conditions' => ['field_a' => 1, 'field_b' => 'something'],
  689. 'limit' => 1,
  690. 'order' => ['a' => 'ASC'],
  691. 'offset' => 5,
  692. 'group' => ['field_a'],
  693. 'having' => ['field_a >' => 100],
  694. 'contain' => ['table_a' => ['table_b']],
  695. 'join' => ['table_a' => ['conditions' => ['a > b']]]
  696. ];
  697. $query = new Query($this->connection, $this->table);
  698. $query->applyOptions($options);
  699. $this->assertEquals(['field_a', 'field_b'], $query->clause('select'));
  700. $expected = new QueryExpression($options['conditions']);
  701. $result = $query->clause('where');
  702. $this->assertEquals($expected, $result);
  703. $this->assertEquals(1, $query->clause('limit'));
  704. $expected = new QueryExpression(['a > b']);
  705. $result = $query->clause('join');
  706. $this->assertEquals([
  707. 'table_a' => ['alias' => 'table_a', 'type' => 'INNER', 'conditions' => $expected]
  708. ], $result);
  709. $expected = new OrderByExpression(['a' => 'ASC']);
  710. $this->assertEquals($expected, $query->clause('order'));
  711. $this->assertEquals(5, $query->clause('offset'));
  712. $this->assertEquals(['field_a'], $query->clause('group'));
  713. $expected = new QueryExpression($options['having']);
  714. $this->assertEquals($expected, $query->clause('having'));
  715. $expected = ['table_a' => ['table_b' => []]];
  716. $this->assertEquals($expected, $query->contain());
  717. }
  718. /**
  719. * ApplyOptions should ignore null values.
  720. *
  721. * @return void
  722. */
  723. public function testApplyOptionsIgnoreNull() {
  724. $options = [
  725. 'fields' => null,
  726. ];
  727. $query = new Query($this->connection, $this->table);
  728. $query->applyOptions($options);
  729. $this->assertEquals([], $query->clause('select'));
  730. }
  731. /**
  732. * Tests getOptions() method
  733. *
  734. * @return void
  735. */
  736. public function testGetOptions() {
  737. $options = ['doABarrelRoll' => true, 'fields' => ['id', 'name']];
  738. $query = new Query($this->connection, $this->table);
  739. $query->applyOptions($options);
  740. $expected = ['doABarrelRoll' => true];
  741. $this->assertEquals($expected, $query->getOptions());
  742. $expected = ['doABarrelRoll' => false, 'doAwesome' => true];
  743. $query->applyOptions($expected);
  744. $this->assertEquals($expected, $query->getOptions());
  745. }
  746. /**
  747. * Tests registering mappers with mapReduce()
  748. *
  749. * @return void
  750. */
  751. public function testMapReduceOnlyMapper() {
  752. $mapper1 = function() {
  753. };
  754. $mapper2 = function() {
  755. };
  756. $query = new Query($this->connection, $this->table);
  757. $this->assertSame($query, $query->mapReduce($mapper1));
  758. $this->assertEquals(
  759. [['mapper' => $mapper1, 'reducer' => null]],
  760. $query->mapReduce()
  761. );
  762. $this->assertEquals($query, $query->mapReduce($mapper1));
  763. $result = $query->mapReduce();
  764. $this->assertEquals(
  765. [
  766. ['mapper' => $mapper1, 'reducer' => null],
  767. ['mapper' => $mapper2, 'reducer' => null]
  768. ],
  769. $result
  770. );
  771. }
  772. /**
  773. * Tests registering mappers and reducers with mapReduce()
  774. *
  775. * @return void
  776. */
  777. public function testMapReduceBothMethods() {
  778. $mapper1 = function() {
  779. };
  780. $mapper2 = function() {
  781. };
  782. $reducer1 = function() {
  783. };
  784. $reducer2 = function() {
  785. };
  786. $query = new Query($this->connection, $this->table);
  787. $this->assertSame($query, $query->mapReduce($mapper1, $reducer1));
  788. $this->assertEquals(
  789. [['mapper' => $mapper1, 'reducer' => $reducer1]],
  790. $query->mapReduce()
  791. );
  792. $this->assertSame($query, $query->mapReduce($mapper2, $reducer2));
  793. $this->assertEquals(
  794. [
  795. ['mapper' => $mapper1, 'reducer' => $reducer1],
  796. ['mapper' => $mapper2, 'reducer' => $reducer2]
  797. ],
  798. $query->mapReduce()
  799. );
  800. }
  801. /**
  802. * Tests that it is possible to overwrite previous map reducers
  803. *
  804. * @return void
  805. */
  806. public function testOverwriteMapReduce() {
  807. $mapper1 = function() {
  808. };
  809. $mapper2 = function() {
  810. };
  811. $reducer1 = function() {
  812. };
  813. $reducer2 = function() {
  814. };
  815. $query = new Query($this->connection, $this->table);
  816. $this->assertEquals($query, $query->mapReduce($mapper1, $reducer1));
  817. $this->assertEquals(
  818. [['mapper' => $mapper1, 'reducer' => $reducer1]],
  819. $query->mapReduce()
  820. );
  821. $this->assertEquals($query, $query->mapReduce($mapper2, $reducer2, true));
  822. $this->assertEquals(
  823. [['mapper' => $mapper2, 'reducer' => $reducer2]],
  824. $query->mapReduce()
  825. );
  826. }
  827. /**
  828. * Tests that multiple map reducers can be stacked
  829. *
  830. * @return void
  831. */
  832. public function testResultsAreWrappedInMapReduce() {
  833. $params = [$this->connection, $this->table];
  834. $query = $this->getMock('\Cake\ORM\Query', ['execute'], $params);
  835. $statement = $this->getMock('\Database\StatementInterface', ['fetch', 'closeCursor']);
  836. $statement->expects($this->exactly(3))
  837. ->method('fetch')
  838. ->will($this->onConsecutiveCalls(['a' => 1], ['a' => 2], false));
  839. $query->expects($this->once())
  840. ->method('execute')
  841. ->will($this->returnValue($statement));
  842. $query->mapReduce(function($v, $k, $mr) {
  843. $mr->emit($v['a']);
  844. });
  845. $query->mapReduce(
  846. function($v, $k, $mr) {
  847. $mr->emitIntermediate($v, $k);
  848. },
  849. function($v, $k, $mr) {
  850. $mr->emit($v[0] + 1);
  851. }
  852. );
  853. $this->assertEquals([2, 3], iterator_to_array($query->all()));
  854. }
  855. /**
  856. * Tests first() method when the query has not been executed before
  857. *
  858. * @return void
  859. */
  860. public function testFirstDirtyQuery() {
  861. $table = TableRegistry::get('articles', ['table' => 'articles']);
  862. $query = new Query($this->connection, $table);
  863. $result = $query->select(['id'])->hydrate(false)->first();
  864. $this->assertEquals(['id' => 1], $result);
  865. $this->assertEquals(1, $query->clause('limit'));
  866. $result = $query->select(['id'])->first();
  867. $this->assertEquals(['id' => 1], $result);
  868. }
  869. /**
  870. * Tests that first can be called again on an already executed query
  871. *
  872. * @return void
  873. */
  874. public function testFirstCleanQuery() {
  875. $table = TableRegistry::get('articles', ['table' => 'articles']);
  876. $query = new Query($this->connection, $table);
  877. $query->select(['id'])->toArray();
  878. $first = $query->hydrate(false)->first();
  879. $this->assertEquals(['id' => 1], $first);
  880. $this->assertEquals(1, $query->clause('limit'));
  881. }
  882. /**
  883. * Tests that first() will not execute the same query twice
  884. *
  885. * @return void
  886. */
  887. public function testFirstSameResult() {
  888. $table = TableRegistry::get('articles', ['table' => 'articles']);
  889. $query = new Query($this->connection, $table);
  890. $query->select(['id'])->toArray();
  891. $first = $query->hydrate(false)->first();
  892. $resultSet = $query->all();
  893. $this->assertEquals(['id' => 1], $first);
  894. $this->assertSame($resultSet, $query->all());
  895. }
  896. /**
  897. * Tests that first can be called against a query with a mapReduce
  898. *
  899. * @return void
  900. */
  901. public function testFirstMapReduce() {
  902. $map = function($row, $key, $mapReduce) {
  903. $mapReduce->emitIntermediate($row['id'], 'id');
  904. };
  905. $reduce = function($values, $key, $mapReduce) {
  906. $mapReduce->emit(array_sum($values));
  907. };
  908. $table = TableRegistry::get('articles', ['table' => 'articles']);
  909. $query = new Query($this->connection, $table);
  910. $query->select(['id'])
  911. ->hydrate(false)
  912. ->mapReduce($map, $reduce);
  913. $first = $query->first();
  914. $this->assertEquals(1, $first);
  915. }
  916. /**
  917. * Testing hydrating a result set into Entity objects
  918. *
  919. * @return void
  920. */
  921. public function testHydrateSimple() {
  922. $table = TableRegistry::get('articles', ['table' => 'articles']);
  923. $query = new Query($this->connection, $table);
  924. $results = $query->select()->toArray();
  925. $this->assertCount(3, $results);
  926. foreach ($results as $r) {
  927. $this->assertInstanceOf('\Cake\ORM\Entity', $r);
  928. }
  929. $first = $results[0];
  930. $this->assertEquals(1, $first->id);
  931. $this->assertEquals(1, $first->author_id);
  932. $this->assertEquals('First Article', $first->title);
  933. $this->assertEquals('First Article Body', $first->body);
  934. $this->assertEquals('Y', $first->published);
  935. }
  936. /**
  937. * Tests that has many results are also hydrated correctly
  938. *
  939. * @return void
  940. */
  941. public function testHydrateWithHasMany() {
  942. $table = TableRegistry::get('authors');
  943. TableRegistry::get('articles');
  944. $table->hasMany('articles', [
  945. 'property' => 'articles',
  946. 'sort' => ['articles.id' => 'asc']
  947. ]);
  948. $query = new Query($this->connection, $table);
  949. $results = $query->select()
  950. ->contain('articles')
  951. ->toArray();
  952. $first = $results[0];
  953. foreach ($first->articles as $r) {
  954. $this->assertInstanceOf('\Cake\ORM\Entity', $r);
  955. }
  956. $this->assertCount(2, $first->articles);
  957. $expected = [
  958. 'id' => 1,
  959. 'title' => 'First Article',
  960. 'body' => 'First Article Body',
  961. 'author_id' => 1,
  962. 'published' => 'Y',
  963. ];
  964. $this->assertEquals($expected, $first->articles[0]->toArray());
  965. $expected = [
  966. 'id' => 3,
  967. 'title' => 'Third Article',
  968. 'author_id' => 1,
  969. 'body' => 'Third Article Body',
  970. 'published' => 'Y',
  971. ];
  972. $this->assertEquals($expected, $first->articles[1]->toArray());
  973. }
  974. /**
  975. * Tests that belongsToMany associations are also correctly hydrated
  976. *
  977. * @return void
  978. */
  979. public function testHydrateBelongsToMany() {
  980. $table = TableRegistry::get('Articles');
  981. TableRegistry::get('Tags');
  982. TableRegistry::get('ArticlesTags', [
  983. 'table' => 'articles_tags'
  984. ]);
  985. $table->belongsToMany('Tags');
  986. $query = new Query($this->connection, $table);
  987. $results = $query
  988. ->select()
  989. ->contain('Tags')
  990. ->toArray();
  991. $first = $results[0];
  992. foreach ($first->tags as $r) {
  993. $this->assertInstanceOf('\Cake\ORM\Entity', $r);
  994. }
  995. $this->assertCount(2, $first->tags);
  996. $expected = [
  997. 'id' => 1,
  998. 'name' => 'tag1',
  999. '_joinData' => ['article_id' => 1, 'tag_id' => 1]
  1000. ];
  1001. $this->assertEquals($expected, $first->tags[0]->toArray());
  1002. $expected = [
  1003. 'id' => 2,
  1004. 'name' => 'tag2',
  1005. '_joinData' => ['article_id' => 1, 'tag_id' => 2]
  1006. ];
  1007. $this->assertEquals($expected, $first->tags[1]->toArray());
  1008. }
  1009. /**
  1010. * Tests that belongsTo relations are correctly hydrated
  1011. *
  1012. * @return void
  1013. */
  1014. public function testHydrateBelongsTo() {
  1015. $table = TableRegistry::get('articles');
  1016. TableRegistry::get('authors');
  1017. $table->belongsTo('authors');
  1018. $query = new Query($this->connection, $table);
  1019. $results = $query->select()
  1020. ->contain('authors')
  1021. ->order(['articles.id' => 'asc'])
  1022. ->toArray();
  1023. $this->assertCount(3, $results);
  1024. $first = $results[0];
  1025. $this->assertInstanceOf('\Cake\ORM\Entity', $first->author);
  1026. $expected = ['id' => 1, 'name' => 'mariano'];
  1027. $this->assertEquals($expected, $first->author->toArray());
  1028. }
  1029. /**
  1030. * Tests that deeply nested associations are also hydrated correctly
  1031. *
  1032. * @return void
  1033. */
  1034. public function testHydrateDeep() {
  1035. $table = TableRegistry::get('authors');
  1036. $article = TableRegistry::get('articles');
  1037. $table->hasMany('articles', [
  1038. 'property' => 'articles',
  1039. 'sort' => ['articles.id' => 'asc']
  1040. ]);
  1041. $article->belongsTo('authors');
  1042. $query = new Query($this->connection, $table);
  1043. $results = $query->select()
  1044. ->contain(['articles' => ['authors']])
  1045. ->toArray();
  1046. $this->assertCount(4, $results);
  1047. $first = $results[0];
  1048. $this->assertInstanceOf('\Cake\ORM\Entity', $first->articles[0]->author);
  1049. $expected = ['id' => 1, 'name' => 'mariano'];
  1050. $this->assertEquals($expected, $first->articles[0]->author->toArray());
  1051. $this->assertFalse(isset($results[3]->articles));
  1052. }
  1053. /**
  1054. * Tests that it is possible to use a custom entity class
  1055. *
  1056. * @return void
  1057. */
  1058. public function testHydrateCustomObject() {
  1059. $class = $this->getMockClass('\Cake\ORM\Entity', ['fakeMethod']);
  1060. $table = TableRegistry::get('articles', [
  1061. 'table' => 'articles',
  1062. 'entityClass' => '\\' . $class
  1063. ]);
  1064. $query = new Query($this->connection, $table);
  1065. $results = $query->select()->toArray();
  1066. $this->assertCount(3, $results);
  1067. foreach ($results as $r) {
  1068. $this->assertInstanceOf($class, $r);
  1069. }
  1070. $first = $results[0];
  1071. $this->assertEquals(1, $first->id);
  1072. $this->assertEquals(1, $first->author_id);
  1073. $this->assertEquals('First Article', $first->title);
  1074. $this->assertEquals('First Article Body', $first->body);
  1075. $this->assertEquals('Y', $first->published);
  1076. }
  1077. /**
  1078. * Tests that has many results are also hydrated correctly
  1079. * when specified a custom entity class
  1080. *
  1081. * @return void
  1082. */
  1083. public function testHydrateWithHasManyCustomEntity() {
  1084. $authorEntity = $this->getMockClass('\Cake\ORM\Entity', ['foo']);
  1085. $articleEntity = $this->getMockClass('\Cake\ORM\Entity', ['foo']);
  1086. $table = TableRegistry::get('authors', [
  1087. 'entityClass' => '\\' . $authorEntity
  1088. ]);
  1089. TableRegistry::get('articles', [
  1090. 'entityClass' => '\\' . $articleEntity
  1091. ]);
  1092. $table->hasMany('articles', [
  1093. 'property' => 'articles',
  1094. 'sort' => ['articles.id' => 'asc']
  1095. ]);
  1096. $query = new Query($this->connection, $table);
  1097. $results = $query->select()
  1098. ->contain('articles')
  1099. ->toArray();
  1100. $first = $results[0];
  1101. $this->assertInstanceOf($authorEntity, $first);
  1102. foreach ($first->articles as $r) {
  1103. $this->assertInstanceOf($articleEntity, $r);
  1104. }
  1105. $this->assertCount(2, $first->articles);
  1106. $expected = [
  1107. 'id' => 1,
  1108. 'title' => 'First Article',
  1109. 'body' => 'First Article Body',
  1110. 'author_id' => 1,
  1111. 'published' => 'Y',
  1112. ];
  1113. $this->assertEquals($expected, $first->articles[0]->toArray());
  1114. }
  1115. /**
  1116. * Tests that belongsTo relations are correctly hydrated into a custom entity class
  1117. *
  1118. * @return void
  1119. */
  1120. public function testHydrateBelongsToCustomEntity() {
  1121. $authorEntity = $this->getMockClass('\Cake\ORM\Entity', ['foo']);
  1122. $table = TableRegistry::get('articles');
  1123. TableRegistry::get('authors', [
  1124. 'entityClass' => '\\' . $authorEntity
  1125. ]);
  1126. $table->belongsTo('authors');
  1127. $query = new Query($this->connection, $table);
  1128. $results = $query->select()
  1129. ->contain('authors')
  1130. ->order(['articles.id' => 'asc'])
  1131. ->toArray();
  1132. $first = $results[0];
  1133. $this->assertInstanceOf($authorEntity, $first->author);
  1134. }
  1135. /**
  1136. * Test getting counts from queries.
  1137. *
  1138. * @return void
  1139. */
  1140. public function testCount() {
  1141. $table = TableRegistry::get('articles');
  1142. $result = $table->find('all')->count();
  1143. $this->assertSame(3, $result);
  1144. $query = $table->find('all')
  1145. ->where(['id >' => 1])
  1146. ->limit(1);
  1147. $result = $query->count();
  1148. $this->assertSame(2, $result);
  1149. $result = $query->all();
  1150. $this->assertCount(1, $result);
  1151. $this->assertEquals(2, $result->first()->id);
  1152. }
  1153. /**
  1154. * Test that count() returns correct results with group by.
  1155. *
  1156. * @return void
  1157. */
  1158. public function testCountWithGroup() {
  1159. $table = TableRegistry::get('articles');
  1160. $query = $table->find('all');
  1161. $query->select(['author_id', 's' => $query->func()->sum('id')])
  1162. ->group(['author_id']);
  1163. $result = $query->count();
  1164. $this->assertEquals(2, $result);
  1165. }
  1166. /**
  1167. * Tests that it is possible to provide a callback for calculating the count
  1168. * of a query
  1169. *
  1170. * @return void
  1171. */
  1172. public function testCountWithCustomCounter() {
  1173. $table = TableRegistry::get('articles');
  1174. $query = $table->find('all');
  1175. $query
  1176. ->select(['author_id', 's' => $query->func()->sum('id')])
  1177. ->where(['id >' => 2])
  1178. ->group(['author_id'])
  1179. ->counter(function($q) use ($query) {
  1180. $this->assertNotSame($q, $query);
  1181. return $q->select([], true)->group([], true)->count();
  1182. });
  1183. $result = $query->count();
  1184. $this->assertEquals(1, $result);
  1185. }
  1186. /**
  1187. * Test update method.
  1188. *
  1189. * @return void
  1190. */
  1191. public function testUpdate() {
  1192. $table = TableRegistry::get('articles');
  1193. $result = $table->query()
  1194. ->update()
  1195. ->set(['title' => 'First'])
  1196. ->execute();
  1197. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1198. $this->assertTrue($result->rowCount() > 0);
  1199. }
  1200. /**
  1201. * Test insert method.
  1202. *
  1203. * @return void
  1204. */
  1205. public function testInsert() {
  1206. $table = TableRegistry::get('articles');
  1207. $result = $table->query()
  1208. ->insert(['title'])
  1209. ->values(['title' => 'First'])
  1210. ->values(['title' => 'Second'])
  1211. ->execute();
  1212. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1213. $this->assertEquals(2, $result->rowCount());
  1214. }
  1215. /**
  1216. * Test delete method.
  1217. *
  1218. * @return void
  1219. */
  1220. public function testDelete() {
  1221. $table = TableRegistry::get('articles');
  1222. $result = $table->query()
  1223. ->delete()
  1224. ->where(['id >=' => 1])
  1225. ->execute();
  1226. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1227. $this->assertTrue($result->rowCount() > 0);
  1228. }
  1229. /**
  1230. * Provides a list of collection methods that can be proxied
  1231. * from the query
  1232. *
  1233. * @return array
  1234. */
  1235. public function collectionMethodsProvider() {
  1236. $identity = function($a) {
  1237. return $a;
  1238. };
  1239. return [
  1240. ['filter', $identity],
  1241. ['reject', $identity],
  1242. ['every', $identity],
  1243. ['some', $identity],
  1244. ['contains', $identity],
  1245. ['map', $identity],
  1246. ['reduce', $identity],
  1247. ['extract', $identity],
  1248. ['max', $identity],
  1249. ['min', $identity],
  1250. ['sortBy', $identity],
  1251. ['groupBy', $identity],
  1252. ['countBy', $identity],
  1253. ['shuffle', $identity],
  1254. ['sample', $identity],
  1255. ['take', 1],
  1256. ['append', new \ArrayIterator],
  1257. ['compile', 1],
  1258. ];
  1259. }
  1260. /**
  1261. * Tests that query can proxy collection methods
  1262. *
  1263. * @dataProvider collectionMethodsProvider
  1264. * @return void
  1265. */
  1266. public function testCollectionProxy($method, $arg) {
  1267. $query = $this->getMock(
  1268. '\Cake\ORM\Query', ['getResults'],
  1269. [$this->connection, $this->table]
  1270. );
  1271. $query->select();
  1272. $resultSet = $this->getMock('\Cake\ORM\ResultSet', [], [$query, null]);
  1273. $query->expects($this->once())
  1274. ->method('getResults')
  1275. ->will($this->returnValue($resultSet));
  1276. $resultSet->expects($this->once())
  1277. ->method($method)
  1278. ->with($arg, 'extra')
  1279. ->will($this->returnValue(new \Cake\Collection\Collection([])));
  1280. $this->assertInstanceOf(
  1281. '\Cake\Collection\Collection',
  1282. $query->{$method}($arg, 'extra')
  1283. );
  1284. }
  1285. /**
  1286. * Tests that calling an inexistent method in query throws an
  1287. * exception
  1288. *
  1289. * @expectedException \BadMethodCallException
  1290. * @expectedExceptionMessage Unknown method "derpFilter"
  1291. * @return void
  1292. */
  1293. public function testCollectionProxyBadMethod() {
  1294. TableRegistry::get('articles')->find('all')->derpFilter();
  1295. }
  1296. /**
  1297. * cache() should fail on non select queries.
  1298. *
  1299. * @expectedException RuntimeException
  1300. * @return void
  1301. */
  1302. public function testCacheErrorOnNonSelect() {
  1303. $table = TableRegistry::get('articles', ['table' => 'articles']);
  1304. $query = new Query($this->connection, $table);
  1305. $query->insert(['test']);
  1306. $query->cache('my_key');
  1307. }
  1308. /**
  1309. * Integration test for query caching.
  1310. *
  1311. * @return void
  1312. */
  1313. public function testCacheReadIntegration() {
  1314. $query = $this->getMock(
  1315. '\Cake\ORM\Query', ['execute'],
  1316. [$this->connection, $this->table]
  1317. );
  1318. $resultSet = $this->getMock('\Cake\ORM\ResultSet', [], [$query, null]);
  1319. $query->expects($this->never())
  1320. ->method('execute');
  1321. $cacher = $this->getMock('Cake\Cache\CacheEngine');
  1322. $cacher->expects($this->once())
  1323. ->method('read')
  1324. ->with('my_key')
  1325. ->will($this->returnValue($resultSet));
  1326. $query->cache('my_key', $cacher)
  1327. ->where(['id' => 1]);
  1328. $results = $query->all();
  1329. $this->assertSame($resultSet, $results);
  1330. }
  1331. /**
  1332. * Integration test for query caching.
  1333. *
  1334. * @return void
  1335. */
  1336. public function testCacheWriteIntegration() {
  1337. $table = TableRegistry::get('Articles');
  1338. $query = new Query($this->connection, $table);
  1339. $query->select(['id', 'title']);
  1340. $cacher = $this->getMock('Cake\Cache\CacheEngine');
  1341. $cacher->expects($this->once())
  1342. ->method('write')
  1343. ->with(
  1344. 'my_key',
  1345. $this->isInstanceOf('Cake\ORM\ResultSet')
  1346. );
  1347. $query->cache('my_key', $cacher)
  1348. ->where(['id' => 1]);
  1349. $query->all();
  1350. }
  1351. /**
  1352. * Integration test to show filtering associations using contain and a closure
  1353. *
  1354. * @return void
  1355. */
  1356. public function testContainWithClosure() {
  1357. $table = TableRegistry::get('authors');
  1358. $table->hasMany('articles');
  1359. $query = new Query($this->connection, $table);
  1360. $query
  1361. ->select()
  1362. ->contain(['articles' => function($q) {
  1363. return $q->where(['articles.id' => 1]);
  1364. }]);
  1365. $ids = [];
  1366. foreach ($query as $entity) {
  1367. foreach ((array)$entity->articles as $article) {
  1368. $ids[] = $article->id;
  1369. }
  1370. }
  1371. $this->assertEquals([1], array_unique($ids));
  1372. }
  1373. /**
  1374. * Tests the formatResults method
  1375. *
  1376. * @return void
  1377. */
  1378. public function testFormatResults() {
  1379. $callback1 = function() {
  1380. };
  1381. $callback2 = function() {
  1382. };
  1383. $table = TableRegistry::get('authors');
  1384. $query = new Query($this->connection, $table);
  1385. $this->assertSame($query, $query->formatResults($callback1));
  1386. $this->assertSame([$callback1], $query->formatResults());
  1387. $this->assertSame($query, $query->formatResults($callback2));
  1388. $this->assertSame([$callback1, $callback2], $query->formatResults());
  1389. $query->formatResults($callback2, true);
  1390. $this->assertSame([$callback2], $query->formatResults());
  1391. $query->formatResults(null, true);
  1392. $this->assertSame([], $query->formatResults());
  1393. $query->formatResults($callback1);
  1394. $query->formatResults($callback2, $query::PREPEND);
  1395. $this->assertSame([$callback2, $callback1], $query->formatResults());
  1396. }
  1397. /**
  1398. * Test fetching results from a qurey with a custom formatter
  1399. *
  1400. * @return void
  1401. */
  1402. public function testQueryWithFormatter() {
  1403. $table = TableRegistry::get('authors');
  1404. $query = new Query($this->connection, $table);
  1405. $query->select()->formatResults(function($results, $q) use ($query) {
  1406. $this->assertSame($query, $q);
  1407. $this->assertInstanceOf('\Cake\ORM\ResultSet', $results);
  1408. return $results->indexBy('id');
  1409. });
  1410. $this->assertEquals([1, 2, 3, 4], array_keys($query->toArray()));
  1411. }
  1412. /**
  1413. * Test fetching results from a qurey with a two custom formatters
  1414. *
  1415. * @return void
  1416. */
  1417. public function testQueryWithStackedFormatters() {
  1418. $table = TableRegistry::get('authors');
  1419. $query = new Query($this->connection, $table);
  1420. $query->select()->formatResults(function($results, $q) use ($query) {
  1421. $this->assertSame($query, $q);
  1422. $this->assertInstanceOf('\Cake\ORM\ResultSet', $results);
  1423. return $results->indexBy('id');
  1424. });
  1425. $query->formatResults(function($results) {
  1426. return $results->extract('name');
  1427. });
  1428. $expected = [
  1429. 1 => 'mariano',
  1430. 2 => 'nate',
  1431. 3 => 'larry',
  1432. 4 => 'garrett'
  1433. ];
  1434. $this->assertEquals($expected, $query->toArray());
  1435. }
  1436. /**
  1437. * Tests that getting results from a query having a contained association
  1438. * will no attach joins twice if count() is called on it afterwards
  1439. *
  1440. * @return void
  1441. */
  1442. public function testCountWithContainCallingAll() {
  1443. $table = TableRegistry::get('articles');
  1444. $table->belongsTo('authors');
  1445. $query = $table->find()
  1446. ->select(['id', 'title'])
  1447. ->contain('authors')
  1448. ->limit(2);
  1449. $results = $query->all();
  1450. $this->assertCount(2, $results);
  1451. $this->assertEquals(3, $query->count());
  1452. }
  1453. /**
  1454. * Tests that it is possible to apply formatters inside the query builder
  1455. * for belongsTo associations
  1456. *
  1457. * @return void
  1458. */
  1459. public function testFormatBelongsToRecords() {
  1460. $table = TableRegistry::get('articles');
  1461. $table->belongsTo('authors');
  1462. $query = $table->find()
  1463. ->contain(['authors' => function($q) {
  1464. return $q
  1465. ->formatResults(function($authors) {
  1466. return $authors->map(function($author) {
  1467. $author->idCopy = $author->id;
  1468. return $author;
  1469. });
  1470. })
  1471. ->formatResults(function($authors) {
  1472. return $authors->map(function($author) {
  1473. $author->idCopy = $author->idCopy + 2;
  1474. return $author;
  1475. });
  1476. });
  1477. }]);
  1478. $query->formatResults(function($results) {
  1479. return $results->combine('id', 'author.idCopy');
  1480. });
  1481. $results = $query->toArray();
  1482. $expected = [1 => 3, 2 => 5, 3 => 3];
  1483. $this->assertEquals($expected, $results);
  1484. }
  1485. }