QueryTest.php 48 KB

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