QueryTest.php 49 KB

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