QueryTest.php 48 KB

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