QueryTest.php 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844
  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. ]
  631. ]
  632. ];
  633. $this->assertEquals($expected, $results);
  634. $query = new Query($this->connection, $table);
  635. $results = $query->select()
  636. ->matching('Tags', function($q) {
  637. return $q->where(['Tags.name' => 'tag2']);
  638. })
  639. ->hydrate(false)
  640. ->toArray();
  641. $expected = [
  642. [
  643. 'id' => 1,
  644. 'title' => 'First Article',
  645. 'body' => 'First Article Body',
  646. 'author_id' => 1,
  647. 'published' => 'Y',
  648. 'tags' => [
  649. 'id' => 2,
  650. 'name' => 'tag2'
  651. ]
  652. ]
  653. ];
  654. $this->assertEquals($expected, $results);
  655. }
  656. /**
  657. * Tests that it is possible to filter by deep associations
  658. *
  659. * @return void
  660. */
  661. public function testMatchingDotNotation() {
  662. $query = new Query($this->connection, $this->table);
  663. $table = TableRegistry::get('authors');
  664. TableRegistry::get('articles');
  665. $table->hasMany('articles');
  666. TableRegistry::get('articles')->belongsToMany('tags');
  667. $results = $query->repository($table)
  668. ->select()
  669. ->hydrate(false)
  670. ->matching('articles.tags', function($q) {
  671. return $q->where(['tags.id' => 2]);
  672. })
  673. ->toArray();
  674. $expected = [
  675. [
  676. 'id' => 1,
  677. 'name' => 'mariano',
  678. 'articles' => [
  679. 'id' => 1,
  680. 'title' => 'First Article',
  681. 'body' => 'First Article Body',
  682. 'author_id' => 1,
  683. 'published' => 'Y',
  684. 'tags' => [
  685. 'id' => 2,
  686. 'name' => 'tag2'
  687. ]
  688. ]
  689. ]
  690. ];
  691. $this->assertEquals($expected, $results);
  692. }
  693. /**
  694. * Test setResult()
  695. *
  696. * @return void
  697. */
  698. public function testSetResult() {
  699. $query = new Query($this->connection, $this->table);
  700. $stmt = $this->getMock('Cake\Database\StatementInterface');
  701. $results = new ResultSet($query, $stmt);
  702. $query->setResult($results);
  703. $this->assertSame($results, $query->all());
  704. }
  705. /**
  706. * Tests that applying array options to a query will convert them
  707. * to equivalent function calls with the correspondent array values
  708. *
  709. * @return void
  710. */
  711. public function testApplyOptions() {
  712. $options = [
  713. 'fields' => ['field_a', 'field_b'],
  714. 'conditions' => ['field_a' => 1, 'field_b' => 'something'],
  715. 'limit' => 1,
  716. 'order' => ['a' => 'ASC'],
  717. 'offset' => 5,
  718. 'group' => ['field_a'],
  719. 'having' => ['field_a >' => 100],
  720. 'contain' => ['table_a' => ['table_b']],
  721. 'join' => ['table_a' => ['conditions' => ['a > b']]]
  722. ];
  723. $query = new Query($this->connection, $this->table);
  724. $query->applyOptions($options);
  725. $this->assertEquals(['field_a', 'field_b'], $query->clause('select'));
  726. $expected = new QueryExpression($options['conditions']);
  727. $result = $query->clause('where');
  728. $this->assertEquals($expected, $result);
  729. $this->assertEquals(1, $query->clause('limit'));
  730. $expected = new QueryExpression(['a > b']);
  731. $result = $query->clause('join');
  732. $this->assertEquals([
  733. 'table_a' => ['alias' => 'table_a', 'type' => 'INNER', 'conditions' => $expected]
  734. ], $result);
  735. $expected = new OrderByExpression(['a' => 'ASC']);
  736. $this->assertEquals($expected, $query->clause('order'));
  737. $this->assertEquals(5, $query->clause('offset'));
  738. $this->assertEquals(['field_a'], $query->clause('group'));
  739. $expected = new QueryExpression($options['having']);
  740. $this->assertEquals($expected, $query->clause('having'));
  741. $expected = ['table_a' => ['table_b' => []]];
  742. $this->assertEquals($expected, $query->contain());
  743. }
  744. /**
  745. * ApplyOptions should ignore null values.
  746. *
  747. * @return void
  748. */
  749. public function testApplyOptionsIgnoreNull() {
  750. $options = [
  751. 'fields' => null,
  752. ];
  753. $query = new Query($this->connection, $this->table);
  754. $query->applyOptions($options);
  755. $this->assertEquals([], $query->clause('select'));
  756. }
  757. /**
  758. * Tests getOptions() method
  759. *
  760. * @return void
  761. */
  762. public function testGetOptions() {
  763. $options = ['doABarrelRoll' => true, 'fields' => ['id', 'name']];
  764. $query = new Query($this->connection, $this->table);
  765. $query->applyOptions($options);
  766. $expected = ['doABarrelRoll' => true];
  767. $this->assertEquals($expected, $query->getOptions());
  768. $expected = ['doABarrelRoll' => false, 'doAwesome' => true];
  769. $query->applyOptions($expected);
  770. $this->assertEquals($expected, $query->getOptions());
  771. }
  772. /**
  773. * Tests registering mappers with mapReduce()
  774. *
  775. * @return void
  776. */
  777. public function testMapReduceOnlyMapper() {
  778. $mapper1 = function() {
  779. };
  780. $mapper2 = function() {
  781. };
  782. $query = new Query($this->connection, $this->table);
  783. $this->assertSame($query, $query->mapReduce($mapper1));
  784. $this->assertEquals(
  785. [['mapper' => $mapper1, 'reducer' => null]],
  786. $query->mapReduce()
  787. );
  788. $this->assertEquals($query, $query->mapReduce($mapper2));
  789. $result = $query->mapReduce();
  790. $this->assertSame(
  791. [
  792. ['mapper' => $mapper1, 'reducer' => null],
  793. ['mapper' => $mapper2, 'reducer' => null]
  794. ],
  795. $result
  796. );
  797. }
  798. /**
  799. * Tests registering mappers and reducers with mapReduce()
  800. *
  801. * @return void
  802. */
  803. public function testMapReduceBothMethods() {
  804. $mapper1 = function() {
  805. };
  806. $mapper2 = function() {
  807. };
  808. $reducer1 = function() {
  809. };
  810. $reducer2 = function() {
  811. };
  812. $query = new Query($this->connection, $this->table);
  813. $this->assertSame($query, $query->mapReduce($mapper1, $reducer1));
  814. $this->assertEquals(
  815. [['mapper' => $mapper1, 'reducer' => $reducer1]],
  816. $query->mapReduce()
  817. );
  818. $this->assertSame($query, $query->mapReduce($mapper2, $reducer2));
  819. $this->assertEquals(
  820. [
  821. ['mapper' => $mapper1, 'reducer' => $reducer1],
  822. ['mapper' => $mapper2, 'reducer' => $reducer2]
  823. ],
  824. $query->mapReduce()
  825. );
  826. }
  827. /**
  828. * Tests that it is possible to overwrite previous map reducers
  829. *
  830. * @return void
  831. */
  832. public function testOverwriteMapReduce() {
  833. $mapper1 = function() {
  834. };
  835. $mapper2 = function() {
  836. };
  837. $reducer1 = function() {
  838. };
  839. $reducer2 = function() {
  840. };
  841. $query = new Query($this->connection, $this->table);
  842. $this->assertEquals($query, $query->mapReduce($mapper1, $reducer1));
  843. $this->assertEquals(
  844. [['mapper' => $mapper1, 'reducer' => $reducer1]],
  845. $query->mapReduce()
  846. );
  847. $this->assertEquals($query, $query->mapReduce($mapper2, $reducer2, true));
  848. $this->assertEquals(
  849. [['mapper' => $mapper2, 'reducer' => $reducer2]],
  850. $query->mapReduce()
  851. );
  852. }
  853. /**
  854. * Tests that multiple map reducers can be stacked
  855. *
  856. * @return void
  857. */
  858. public function testResultsAreWrappedInMapReduce() {
  859. $params = [$this->connection, $this->table];
  860. $query = $this->getMock('\Cake\ORM\Query', ['execute'], $params);
  861. $statement = $this->getMock(
  862. '\Database\StatementInterface',
  863. ['fetch', 'closeCursor', 'rowCount']
  864. );
  865. $statement->expects($this->exactly(3))
  866. ->method('fetch')
  867. ->will($this->onConsecutiveCalls(['a' => 1], ['a' => 2], false));
  868. $query->expects($this->once())
  869. ->method('execute')
  870. ->will($this->returnValue($statement));
  871. $query->mapReduce(function($v, $k, $mr) {
  872. $mr->emit($v['a']);
  873. });
  874. $query->mapReduce(
  875. function($v, $k, $mr) {
  876. $mr->emitIntermediate($v, $k);
  877. },
  878. function($v, $k, $mr) {
  879. $mr->emit($v[0] + 1);
  880. }
  881. );
  882. $this->assertEquals([2, 3], iterator_to_array($query->all()));
  883. }
  884. /**
  885. * Tests first() method when the query has not been executed before
  886. *
  887. * @return void
  888. */
  889. public function testFirstDirtyQuery() {
  890. $table = TableRegistry::get('articles', ['table' => 'articles']);
  891. $query = new Query($this->connection, $table);
  892. $result = $query->select(['id'])->hydrate(false)->first();
  893. $this->assertEquals(['id' => 1], $result);
  894. $this->assertEquals(1, $query->clause('limit'));
  895. $result = $query->select(['id'])->first();
  896. $this->assertEquals(['id' => 1], $result);
  897. }
  898. /**
  899. * Tests that first can be called again on an already executed query
  900. *
  901. * @return void
  902. */
  903. public function testFirstCleanQuery() {
  904. $table = TableRegistry::get('articles', ['table' => 'articles']);
  905. $query = new Query($this->connection, $table);
  906. $query->select(['id'])->toArray();
  907. $first = $query->hydrate(false)->first();
  908. $this->assertEquals(['id' => 1], $first);
  909. $this->assertEquals(1, $query->clause('limit'));
  910. }
  911. /**
  912. * Tests that first() will not execute the same query twice
  913. *
  914. * @return void
  915. */
  916. public function testFirstSameResult() {
  917. $table = TableRegistry::get('articles', ['table' => 'articles']);
  918. $query = new Query($this->connection, $table);
  919. $query->select(['id'])->toArray();
  920. $first = $query->hydrate(false)->first();
  921. $resultSet = $query->all();
  922. $this->assertEquals(['id' => 1], $first);
  923. $this->assertSame($resultSet, $query->all());
  924. }
  925. /**
  926. * Tests that first can be called against a query with a mapReduce
  927. *
  928. * @return void
  929. */
  930. public function testFirstMapReduce() {
  931. $map = function($row, $key, $mapReduce) {
  932. $mapReduce->emitIntermediate($row['id'], 'id');
  933. };
  934. $reduce = function($values, $key, $mapReduce) {
  935. $mapReduce->emit(array_sum($values));
  936. };
  937. $table = TableRegistry::get('articles', ['table' => 'articles']);
  938. $query = new Query($this->connection, $table);
  939. $query->select(['id'])
  940. ->hydrate(false)
  941. ->mapReduce($map, $reduce);
  942. $first = $query->first();
  943. $this->assertEquals(1, $first);
  944. }
  945. /**
  946. * Testing hydrating a result set into Entity objects
  947. *
  948. * @return void
  949. */
  950. public function testHydrateSimple() {
  951. $table = TableRegistry::get('articles', ['table' => 'articles']);
  952. $query = new Query($this->connection, $table);
  953. $results = $query->select()->toArray();
  954. $this->assertCount(3, $results);
  955. foreach ($results as $r) {
  956. $this->assertInstanceOf('\Cake\ORM\Entity', $r);
  957. }
  958. $first = $results[0];
  959. $this->assertEquals(1, $first->id);
  960. $this->assertEquals(1, $first->author_id);
  961. $this->assertEquals('First Article', $first->title);
  962. $this->assertEquals('First Article Body', $first->body);
  963. $this->assertEquals('Y', $first->published);
  964. }
  965. /**
  966. * Tests that has many results are also hydrated correctly
  967. *
  968. * @return void
  969. */
  970. public function testHydrateWithHasMany() {
  971. $table = TableRegistry::get('authors');
  972. TableRegistry::get('articles');
  973. $table->hasMany('articles', [
  974. 'propertyName' => 'articles',
  975. 'sort' => ['articles.id' => 'asc']
  976. ]);
  977. $query = new Query($this->connection, $table);
  978. $results = $query->select()
  979. ->contain('articles')
  980. ->toArray();
  981. $first = $results[0];
  982. foreach ($first->articles as $r) {
  983. $this->assertInstanceOf('\Cake\ORM\Entity', $r);
  984. }
  985. $this->assertCount(2, $first->articles);
  986. $expected = [
  987. 'id' => 1,
  988. 'title' => 'First Article',
  989. 'body' => 'First Article Body',
  990. 'author_id' => 1,
  991. 'published' => 'Y',
  992. ];
  993. $this->assertEquals($expected, $first->articles[0]->toArray());
  994. $expected = [
  995. 'id' => 3,
  996. 'title' => 'Third Article',
  997. 'author_id' => 1,
  998. 'body' => 'Third Article Body',
  999. 'published' => 'Y',
  1000. ];
  1001. $this->assertEquals($expected, $first->articles[1]->toArray());
  1002. }
  1003. /**
  1004. * Tests that belongsToMany associations are also correctly hydrated
  1005. *
  1006. * @return void
  1007. */
  1008. public function testHydrateBelongsToMany() {
  1009. $table = TableRegistry::get('Articles');
  1010. TableRegistry::get('Tags');
  1011. TableRegistry::get('ArticlesTags', [
  1012. 'table' => 'articles_tags'
  1013. ]);
  1014. $table->belongsToMany('Tags');
  1015. $query = new Query($this->connection, $table);
  1016. $results = $query
  1017. ->select()
  1018. ->contain('Tags')
  1019. ->toArray();
  1020. $first = $results[0];
  1021. foreach ($first->tags as $r) {
  1022. $this->assertInstanceOf('\Cake\ORM\Entity', $r);
  1023. }
  1024. $this->assertCount(2, $first->tags);
  1025. $expected = [
  1026. 'id' => 1,
  1027. 'name' => 'tag1',
  1028. '_joinData' => ['article_id' => 1, 'tag_id' => 1]
  1029. ];
  1030. $this->assertEquals($expected, $first->tags[0]->toArray());
  1031. $expected = [
  1032. 'id' => 2,
  1033. 'name' => 'tag2',
  1034. '_joinData' => ['article_id' => 1, 'tag_id' => 2]
  1035. ];
  1036. $this->assertEquals($expected, $first->tags[1]->toArray());
  1037. }
  1038. /**
  1039. * Tests that belongsTo relations are correctly hydrated
  1040. *
  1041. * @return void
  1042. */
  1043. public function testHydrateBelongsTo() {
  1044. $table = TableRegistry::get('articles');
  1045. TableRegistry::get('authors');
  1046. $table->belongsTo('authors');
  1047. $query = new Query($this->connection, $table);
  1048. $results = $query->select()
  1049. ->contain('authors')
  1050. ->order(['articles.id' => 'asc'])
  1051. ->toArray();
  1052. $this->assertCount(3, $results);
  1053. $first = $results[0];
  1054. $this->assertInstanceOf('\Cake\ORM\Entity', $first->author);
  1055. $expected = ['id' => 1, 'name' => 'mariano'];
  1056. $this->assertEquals($expected, $first->author->toArray());
  1057. }
  1058. /**
  1059. * Tests that deeply nested associations are also hydrated correctly
  1060. *
  1061. * @return void
  1062. */
  1063. public function testHydrateDeep() {
  1064. $table = TableRegistry::get('authors');
  1065. $article = TableRegistry::get('articles');
  1066. $table->hasMany('articles', [
  1067. 'propertyName' => 'articles',
  1068. 'sort' => ['articles.id' => 'asc']
  1069. ]);
  1070. $article->belongsTo('authors');
  1071. $query = new Query($this->connection, $table);
  1072. $results = $query->select()
  1073. ->contain(['articles' => ['authors']])
  1074. ->toArray();
  1075. $this->assertCount(4, $results);
  1076. $first = $results[0];
  1077. $this->assertInstanceOf('\Cake\ORM\Entity', $first->articles[0]->author);
  1078. $expected = ['id' => 1, 'name' => 'mariano'];
  1079. $this->assertEquals($expected, $first->articles[0]->author->toArray());
  1080. $this->assertFalse(isset($results[3]->articles));
  1081. }
  1082. /**
  1083. * Tests that it is possible to use a custom entity class
  1084. *
  1085. * @return void
  1086. */
  1087. public function testHydrateCustomObject() {
  1088. $class = $this->getMockClass('\Cake\ORM\Entity', ['fakeMethod']);
  1089. $table = TableRegistry::get('articles', [
  1090. 'table' => 'articles',
  1091. 'entityClass' => '\\' . $class
  1092. ]);
  1093. $query = new Query($this->connection, $table);
  1094. $results = $query->select()->toArray();
  1095. $this->assertCount(3, $results);
  1096. foreach ($results as $r) {
  1097. $this->assertInstanceOf($class, $r);
  1098. }
  1099. $first = $results[0];
  1100. $this->assertEquals(1, $first->id);
  1101. $this->assertEquals(1, $first->author_id);
  1102. $this->assertEquals('First Article', $first->title);
  1103. $this->assertEquals('First Article Body', $first->body);
  1104. $this->assertEquals('Y', $first->published);
  1105. }
  1106. /**
  1107. * Tests that has many results are also hydrated correctly
  1108. * when specified a custom entity class
  1109. *
  1110. * @return void
  1111. */
  1112. public function testHydrateWithHasManyCustomEntity() {
  1113. $authorEntity = $this->getMockClass('\Cake\ORM\Entity', ['foo']);
  1114. $articleEntity = $this->getMockClass('\Cake\ORM\Entity', ['foo']);
  1115. $table = TableRegistry::get('authors', [
  1116. 'entityClass' => '\\' . $authorEntity
  1117. ]);
  1118. TableRegistry::get('articles', [
  1119. 'entityClass' => '\\' . $articleEntity
  1120. ]);
  1121. $table->hasMany('articles', [
  1122. 'propertyName' => 'articles',
  1123. 'sort' => ['articles.id' => 'asc']
  1124. ]);
  1125. $query = new Query($this->connection, $table);
  1126. $results = $query->select()
  1127. ->contain('articles')
  1128. ->toArray();
  1129. $first = $results[0];
  1130. $this->assertInstanceOf($authorEntity, $first);
  1131. foreach ($first->articles as $r) {
  1132. $this->assertInstanceOf($articleEntity, $r);
  1133. }
  1134. $this->assertCount(2, $first->articles);
  1135. $expected = [
  1136. 'id' => 1,
  1137. 'title' => 'First Article',
  1138. 'body' => 'First Article Body',
  1139. 'author_id' => 1,
  1140. 'published' => 'Y',
  1141. ];
  1142. $this->assertEquals($expected, $first->articles[0]->toArray());
  1143. }
  1144. /**
  1145. * Tests that belongsTo relations are correctly hydrated into a custom entity class
  1146. *
  1147. * @return void
  1148. */
  1149. public function testHydrateBelongsToCustomEntity() {
  1150. $authorEntity = $this->getMockClass('\Cake\ORM\Entity', ['foo']);
  1151. $table = TableRegistry::get('articles');
  1152. TableRegistry::get('authors', [
  1153. 'entityClass' => '\\' . $authorEntity
  1154. ]);
  1155. $table->belongsTo('authors');
  1156. $query = new Query($this->connection, $table);
  1157. $results = $query->select()
  1158. ->contain('authors')
  1159. ->order(['articles.id' => 'asc'])
  1160. ->toArray();
  1161. $first = $results[0];
  1162. $this->assertInstanceOf($authorEntity, $first->author);
  1163. }
  1164. /**
  1165. * Test getting counts from queries.
  1166. *
  1167. * @return void
  1168. */
  1169. public function testCount() {
  1170. $table = TableRegistry::get('articles');
  1171. $result = $table->find('all')->count();
  1172. $this->assertSame(3, $result);
  1173. $query = $table->find('all')
  1174. ->where(['id >' => 1])
  1175. ->limit(1);
  1176. $result = $query->count();
  1177. $this->assertSame(2, $result);
  1178. $result = $query->all();
  1179. $this->assertCount(1, $result);
  1180. $this->assertEquals(2, $result->first()->id);
  1181. }
  1182. /**
  1183. * Test that count() returns correct results with group by.
  1184. *
  1185. * @return void
  1186. */
  1187. public function testCountWithGroup() {
  1188. $table = TableRegistry::get('articles');
  1189. $query = $table->find('all');
  1190. $query->select(['author_id', 's' => $query->func()->sum('id')])
  1191. ->group(['author_id']);
  1192. $result = $query->count();
  1193. $this->assertEquals(2, $result);
  1194. }
  1195. /**
  1196. * Tests that it is possible to provide a callback for calculating the count
  1197. * of a query
  1198. *
  1199. * @return void
  1200. */
  1201. public function testCountWithCustomCounter() {
  1202. $table = TableRegistry::get('articles');
  1203. $query = $table->find('all');
  1204. $query
  1205. ->select(['author_id', 's' => $query->func()->sum('id')])
  1206. ->where(['id >' => 2])
  1207. ->group(['author_id'])
  1208. ->counter(function($q) use ($query) {
  1209. $this->assertNotSame($q, $query);
  1210. return $q->select([], true)->group([], true)->count();
  1211. });
  1212. $result = $query->count();
  1213. $this->assertEquals(1, $result);
  1214. }
  1215. /**
  1216. * Test update method.
  1217. *
  1218. * @return void
  1219. */
  1220. public function testUpdate() {
  1221. $table = TableRegistry::get('articles');
  1222. $result = $table->query()
  1223. ->update()
  1224. ->set(['title' => 'First'])
  1225. ->execute();
  1226. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1227. $this->assertTrue($result->rowCount() > 0);
  1228. }
  1229. /**
  1230. * Test insert method.
  1231. *
  1232. * @return void
  1233. */
  1234. public function testInsert() {
  1235. $table = TableRegistry::get('articles');
  1236. $result = $table->query()
  1237. ->insert(['title'])
  1238. ->values(['title' => 'First'])
  1239. ->values(['title' => 'Second'])
  1240. ->execute();
  1241. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1242. $this->assertEquals(2, $result->rowCount());
  1243. }
  1244. /**
  1245. * Test delete method.
  1246. *
  1247. * @return void
  1248. */
  1249. public function testDelete() {
  1250. $table = TableRegistry::get('articles');
  1251. $result = $table->query()
  1252. ->delete()
  1253. ->where(['id >=' => 1])
  1254. ->execute();
  1255. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1256. $this->assertTrue($result->rowCount() > 0);
  1257. }
  1258. /**
  1259. * Provides a list of collection methods that can be proxied
  1260. * from the query
  1261. *
  1262. * @return array
  1263. */
  1264. public function collectionMethodsProvider() {
  1265. $identity = function($a) {
  1266. return $a;
  1267. };
  1268. return [
  1269. ['filter', $identity],
  1270. ['reject', $identity],
  1271. ['every', $identity],
  1272. ['some', $identity],
  1273. ['contains', $identity],
  1274. ['map', $identity],
  1275. ['reduce', $identity],
  1276. ['extract', $identity],
  1277. ['max', $identity],
  1278. ['min', $identity],
  1279. ['sortBy', $identity],
  1280. ['groupBy', $identity],
  1281. ['countBy', $identity],
  1282. ['shuffle', $identity],
  1283. ['sample', $identity],
  1284. ['take', 1],
  1285. ['append', new \ArrayIterator],
  1286. ['compile', 1],
  1287. ];
  1288. }
  1289. /**
  1290. * Tests that query can proxy collection methods
  1291. *
  1292. * @dataProvider collectionMethodsProvider
  1293. * @return void
  1294. */
  1295. public function testCollectionProxy($method, $arg) {
  1296. $query = $this->getMock(
  1297. '\Cake\ORM\Query', ['all'],
  1298. [$this->connection, $this->table]
  1299. );
  1300. $query->select();
  1301. $resultSet = $this->getMock('\Cake\ORM\ResultSet', [], [$query, null]);
  1302. $query->expects($this->once())
  1303. ->method('all')
  1304. ->will($this->returnValue($resultSet));
  1305. $resultSet->expects($this->once())
  1306. ->method($method)
  1307. ->with($arg, 'extra')
  1308. ->will($this->returnValue(new \Cake\Collection\Collection([])));
  1309. $this->assertInstanceOf(
  1310. '\Cake\Collection\Collection',
  1311. $query->{$method}($arg, 'extra')
  1312. );
  1313. }
  1314. /**
  1315. * Tests that calling an inexistent method in query throws an
  1316. * exception
  1317. *
  1318. * @expectedException \BadMethodCallException
  1319. * @expectedExceptionMessage Unknown method "derpFilter"
  1320. * @return void
  1321. */
  1322. public function testCollectionProxyBadMethod() {
  1323. TableRegistry::get('articles')->find('all')->derpFilter();
  1324. }
  1325. /**
  1326. * cache() should fail on non select queries.
  1327. *
  1328. * @expectedException RuntimeException
  1329. * @return void
  1330. */
  1331. public function testCacheErrorOnNonSelect() {
  1332. $table = TableRegistry::get('articles', ['table' => 'articles']);
  1333. $query = new Query($this->connection, $table);
  1334. $query->insert(['test']);
  1335. $query->cache('my_key');
  1336. }
  1337. /**
  1338. * Integration test for query caching.
  1339. *
  1340. * @return void
  1341. */
  1342. public function testCacheReadIntegration() {
  1343. $query = $this->getMock(
  1344. '\Cake\ORM\Query', ['execute'],
  1345. [$this->connection, $this->table]
  1346. );
  1347. $resultSet = $this->getMock('\Cake\ORM\ResultSet', [], [$query, null]);
  1348. $query->expects($this->never())
  1349. ->method('execute');
  1350. $cacher = $this->getMock('Cake\Cache\CacheEngine');
  1351. $cacher->expects($this->once())
  1352. ->method('read')
  1353. ->with('my_key')
  1354. ->will($this->returnValue($resultSet));
  1355. $query->cache('my_key', $cacher)
  1356. ->where(['id' => 1]);
  1357. $results = $query->all();
  1358. $this->assertSame($resultSet, $results);
  1359. }
  1360. /**
  1361. * Integration test for query caching.
  1362. *
  1363. * @return void
  1364. */
  1365. public function testCacheWriteIntegration() {
  1366. $table = TableRegistry::get('Articles');
  1367. $query = new Query($this->connection, $table);
  1368. $query->select(['id', 'title']);
  1369. $cacher = $this->getMock('Cake\Cache\CacheEngine');
  1370. $cacher->expects($this->once())
  1371. ->method('write')
  1372. ->with(
  1373. 'my_key',
  1374. $this->isInstanceOf('Cake\ORM\ResultSet')
  1375. );
  1376. $query->cache('my_key', $cacher)
  1377. ->where(['id' => 1]);
  1378. $query->all();
  1379. }
  1380. /**
  1381. * Integration test to show filtering associations using contain and a closure
  1382. *
  1383. * @return void
  1384. */
  1385. public function testContainWithClosure() {
  1386. $table = TableRegistry::get('authors');
  1387. $table->hasMany('articles');
  1388. $query = new Query($this->connection, $table);
  1389. $query
  1390. ->select()
  1391. ->contain(['articles' => function($q) {
  1392. return $q->where(['articles.id' => 1]);
  1393. }]);
  1394. $ids = [];
  1395. foreach ($query as $entity) {
  1396. foreach ((array)$entity->articles as $article) {
  1397. $ids[] = $article->id;
  1398. }
  1399. }
  1400. $this->assertEquals([1], array_unique($ids));
  1401. }
  1402. /**
  1403. * Tests the formatResults method
  1404. *
  1405. * @return void
  1406. */
  1407. public function testFormatResults() {
  1408. $callback1 = function() {
  1409. };
  1410. $callback2 = function() {
  1411. };
  1412. $table = TableRegistry::get('authors');
  1413. $query = new Query($this->connection, $table);
  1414. $this->assertSame($query, $query->formatResults($callback1));
  1415. $this->assertSame([$callback1], $query->formatResults());
  1416. $this->assertSame($query, $query->formatResults($callback2));
  1417. $this->assertSame([$callback1, $callback2], $query->formatResults());
  1418. $query->formatResults($callback2, true);
  1419. $this->assertSame([$callback2], $query->formatResults());
  1420. $query->formatResults(null, true);
  1421. $this->assertSame([], $query->formatResults());
  1422. $query->formatResults($callback1);
  1423. $query->formatResults($callback2, $query::PREPEND);
  1424. $this->assertSame([$callback2, $callback1], $query->formatResults());
  1425. }
  1426. /**
  1427. * Test fetching results from a qurey with a custom formatter
  1428. *
  1429. * @return void
  1430. */
  1431. public function testQueryWithFormatter() {
  1432. $table = TableRegistry::get('authors');
  1433. $query = new Query($this->connection, $table);
  1434. $query->select()->formatResults(function($results, $q) use ($query) {
  1435. $this->assertSame($query, $q);
  1436. $this->assertInstanceOf('\Cake\ORM\ResultSet', $results);
  1437. return $results->indexBy('id');
  1438. });
  1439. $this->assertEquals([1, 2, 3, 4], array_keys($query->toArray()));
  1440. }
  1441. /**
  1442. * Test fetching results from a qurey with a two custom formatters
  1443. *
  1444. * @return void
  1445. */
  1446. public function testQueryWithStackedFormatters() {
  1447. $table = TableRegistry::get('authors');
  1448. $query = new Query($this->connection, $table);
  1449. $query->select()->formatResults(function($results, $q) use ($query) {
  1450. $this->assertSame($query, $q);
  1451. $this->assertInstanceOf('\Cake\ORM\ResultSet', $results);
  1452. return $results->indexBy('id');
  1453. });
  1454. $query->formatResults(function($results) {
  1455. return $results->extract('name');
  1456. });
  1457. $expected = [
  1458. 1 => 'mariano',
  1459. 2 => 'nate',
  1460. 3 => 'larry',
  1461. 4 => 'garrett'
  1462. ];
  1463. $this->assertEquals($expected, $query->toArray());
  1464. }
  1465. /**
  1466. * Tests that getting results from a query having a contained association
  1467. * will no attach joins twice if count() is called on it afterwards
  1468. *
  1469. * @return void
  1470. */
  1471. public function testCountWithContainCallingAll() {
  1472. $table = TableRegistry::get('articles');
  1473. $table->belongsTo('authors');
  1474. $query = $table->find()
  1475. ->select(['id', 'title'])
  1476. ->contain('authors')
  1477. ->limit(2);
  1478. $results = $query->all();
  1479. $this->assertCount(2, $results);
  1480. $this->assertEquals(3, $query->count());
  1481. }
  1482. /**
  1483. * Tests that it is possible to apply formatters inside the query builder
  1484. * for belongsTo associations
  1485. *
  1486. * @return void
  1487. */
  1488. public function testFormatBelongsToRecords() {
  1489. $table = TableRegistry::get('articles');
  1490. $table->belongsTo('authors');
  1491. $query = $table->find()
  1492. ->contain(['authors' => function($q) {
  1493. return $q
  1494. ->formatResults(function($authors) {
  1495. return $authors->map(function($author) {
  1496. $author->idCopy = $author->id;
  1497. return $author;
  1498. });
  1499. })
  1500. ->formatResults(function($authors) {
  1501. return $authors->map(function($author) {
  1502. $author->idCopy = $author->idCopy + 2;
  1503. return $author;
  1504. });
  1505. });
  1506. }]);
  1507. $query->formatResults(function($results) {
  1508. return $results->combine('id', 'author.idCopy');
  1509. });
  1510. $results = $query->toArray();
  1511. $expected = [1 => 3, 2 => 5, 3 => 3];
  1512. $this->assertEquals($expected, $results);
  1513. }
  1514. /**
  1515. * Tests it is possible to apply formatters to deep relations.
  1516. *
  1517. * @return void
  1518. */
  1519. public function testFormatDeepAssocationRecords() {
  1520. $table = TableRegistry::get('ArticlesTags');
  1521. $table->belongsTo('Articles');
  1522. $table->association('Articles')->target()->belongsTo('Authors');
  1523. $builder = function($q) {
  1524. return $q
  1525. ->formatResults(function($results) {
  1526. return $results->map(function($result) {
  1527. $result->idCopy = $result->id;
  1528. return $result;
  1529. });
  1530. })
  1531. ->formatResults(function($results) {
  1532. return $results->map(function($result) {
  1533. $result->idCopy = $result->idCopy + 2;
  1534. return $result;
  1535. });
  1536. });
  1537. };
  1538. $query = $table->find()
  1539. ->contain(['Articles' => $builder, 'Articles.Authors' => $builder]);
  1540. $query->formatResults(function($results) {
  1541. return $results->map(function($row) {
  1542. return sprintf(
  1543. '%s - %s - %s',
  1544. $row->tag_id,
  1545. $row->article->idCopy,
  1546. $row->article->author->idCopy
  1547. );
  1548. });
  1549. });
  1550. $expected = ['1 - 3 - 3', '2 - 3 - 3', '1 - 4 - 5', '3 - 4 - 5'];
  1551. $this->assertEquals($expected, $query->toArray());
  1552. }
  1553. /**
  1554. * Tests that formatters cna be applied to deep associaitons that are fetched using
  1555. * additional queries
  1556. *
  1557. * @return void
  1558. */
  1559. public function testFormatDeepDistantAssociationRecords() {
  1560. $table = TableRegistry::get('authors');
  1561. $table->hasMany('articles');
  1562. $articles = $table->association('articles')->target();
  1563. $articles->hasMany('articlesTags');
  1564. $articles->association('articlesTags')->target()->belongsTo('tags');
  1565. $query = $table->find()->contain(['articles.articlesTags.tags' => function($q) {
  1566. return $q->formatResults(function($results) {
  1567. return $results->map(function($tag) {
  1568. $tag->name .= ' - visited';
  1569. return $tag;
  1570. });
  1571. });
  1572. }]);
  1573. $query->mapReduce(function($row, $key, $mr) {
  1574. foreach ((array)$row->articles as $article) {
  1575. foreach ((array)$article->articles_tags as $articleTag) {
  1576. $mr->emit($articleTag->tag->name);
  1577. }
  1578. }
  1579. });
  1580. $expected = ['tag1 - visited', 'tag2 - visited', 'tag1 - visited', 'tag3 - visited'];
  1581. $this->assertEquals($expected, $query->toArray());
  1582. }
  1583. /**
  1584. * Tests that it is possible to attach more association when using a query
  1585. * builder for other associaitons
  1586. *
  1587. * @return void
  1588. */
  1589. public function testContainInAssociationQuery() {
  1590. $table = TableRegistry::get('ArticlesTags');
  1591. $table->belongsTo('Articles');
  1592. $table->association('Articles')->target()->belongsTo('Authors');
  1593. $query = $table->find()->contain(['Articles' => function($q) {
  1594. return $q->contain('Authors');
  1595. }]);
  1596. $results = $query->extract('article.author.name')->toArray();
  1597. $expected = ['mariano', 'mariano', 'larry', 'larry'];
  1598. $this->assertEquals($expected, $results);
  1599. }
  1600. /**
  1601. * Tests that it is possible to apply more `matching` conditions inside query
  1602. * builders for associations
  1603. *
  1604. * @return void
  1605. */
  1606. public function testContainInAssociationMatching() {
  1607. $table = TableRegistry::get('authors');
  1608. $table->hasMany('articles');
  1609. $articles = $table->association('articles')->target();
  1610. $articles->hasMany('articlesTags');
  1611. $articles->association('articlesTags')->target()->belongsTo('tags');
  1612. $query = $table->find()->matching('articles.articlesTags', function($q) {
  1613. return $q->matching('tags', function($q) {
  1614. return $q->where(['tags.name' => 'tag3']);
  1615. });
  1616. });
  1617. $results = $query->toArray();
  1618. $this->assertCount(1, $results);
  1619. $this->assertEquals('tag3', $results[0]->articles->articles_tags->tag->name);
  1620. }
  1621. /**
  1622. * Tests __debugInfo
  1623. *
  1624. * @return void
  1625. */
  1626. public function testDebugInfo() {
  1627. $table = TableRegistry::get('authors');
  1628. $table->hasMany('articles');
  1629. $query = $table->find()
  1630. ->where(['id > ' => 1])
  1631. ->bufferResults(false)
  1632. ->hydrate(false)
  1633. ->matching('articles')
  1634. ->applyOptions(['foo' => 'bar'])
  1635. ->formatResults(function($results) {
  1636. return $results;
  1637. })
  1638. ->mapReduce(function($item, $key, $mr) {
  1639. $mr->emit($item);
  1640. });
  1641. $expected = [
  1642. 'sql' => $query->sql(),
  1643. 'params' => $query->valueBinder()->bindings(),
  1644. 'defaultTypes' => [
  1645. 'authors.id' => 'integer',
  1646. 'id' => 'integer',
  1647. 'authors.name' => 'string',
  1648. 'name' => 'string'
  1649. ],
  1650. 'decorators' => 0,
  1651. 'executed' => false,
  1652. 'hydrate' => false,
  1653. 'buffered' => false,
  1654. 'formatters' => 1,
  1655. 'mapReducers' => 1,
  1656. 'contain' => [
  1657. 'articles' => [
  1658. 'queryBuilder' => null,
  1659. 'matching' => true
  1660. ]
  1661. ],
  1662. 'extraOptions' => ['foo' => 'bar'],
  1663. 'repository' => $table
  1664. ];
  1665. $this->assertSame($expected, $query->__debugInfo());
  1666. }
  1667. /**
  1668. * Tests that the eagerLoaded function works and is transmitted correctly to eagerly
  1669. * loaded associations
  1670. *
  1671. * @return void
  1672. */
  1673. public function testEagerLoaded() {
  1674. $table = TableRegistry::get('authors');
  1675. $table->hasMany('articles');
  1676. $query = $table->find()->contain(['articles' => function($q) {
  1677. $this->assertTrue($q->eagerLoaded());
  1678. return $q;
  1679. }]);
  1680. $this->assertFalse($query->eagerLoaded());
  1681. $table->getEventManager()->attach(function($e, $q, $o, $primary) {
  1682. $this->assertTrue($primary);
  1683. }, 'Model.beforeFind');
  1684. TableRegistry::get('articles')
  1685. ->getEventManager()->attach(function($e, $q, $o, $primary) {
  1686. $this->assertFalse($primary);
  1687. }, 'Model.beforeFind');
  1688. $query->all();
  1689. }
  1690. }