QueryTest.php 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706
  1. <?php
  2. /**
  3. * PHP Version 5.4
  4. *
  5. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  6. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * For full copyright and license information, please see the LICENSE.txt
  10. * Redistributions of files must retain the above copyright notice.
  11. *
  12. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  13. * @link http://cakephp.org CakePHP(tm) Project
  14. * @since CakePHP(tm) v 3.0.0
  15. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  16. */
  17. namespace Cake\Test\TestCase\ORM;
  18. use Cake\Core\Configure;
  19. use Cake\Database\ConnectionManager;
  20. use Cake\Database\Expression\IdentifierExpression;
  21. use Cake\Database\Expression\OrderByExpression;
  22. use Cake\Database\Expression\QueryExpression;
  23. use Cake\ORM\Query;
  24. use Cake\ORM\ResultSet;
  25. use Cake\ORM\Table;
  26. use Cake\ORM\TableRegistry;
  27. use Cake\TestSuite\TestCase;
  28. /**
  29. * Tests Query class
  30. *
  31. */
  32. class QueryTest extends TestCase {
  33. /**
  34. * Fixture to be used
  35. *
  36. * @var array
  37. */
  38. public $fixtures = ['core.article', 'core.author', 'core.tag',
  39. 'core.articles_tag', 'core.post'];
  40. /**
  41. * setUp method
  42. *
  43. * @return void
  44. */
  45. public function setUp() {
  46. parent::setUp();
  47. $this->connection = ConnectionManager::get('test');
  48. $schema = [
  49. 'id' => ['type' => 'integer'],
  50. '_constraints' => [
  51. 'primary' => ['type' => 'primary', 'columns' => ['id']]
  52. ]
  53. ];
  54. $schema1 = [
  55. 'id' => ['type' => 'integer'],
  56. 'name' => ['type' => 'string'],
  57. 'phone' => ['type' => 'string'],
  58. '_constraints' => [
  59. 'primary' => ['type' => 'primary', 'columns' => ['id']]
  60. ]
  61. ];
  62. $schema2 = [
  63. 'id' => ['type' => 'integer'],
  64. 'total' => ['type' => 'string'],
  65. 'placed' => ['type' => 'datetime'],
  66. '_constraints' => [
  67. 'primary' => ['type' => 'primary', 'columns' => ['id']]
  68. ]
  69. ];
  70. $this->table = $table = TableRegistry::get('foo', ['schema' => $schema]);
  71. $clients = TableRegistry::get('clients', ['schema' => $schema1]);
  72. $orders = TableRegistry::get('orders', ['schema' => $schema2]);
  73. $companies = TableRegistry::get('companies', ['schema' => $schema, 'table' => 'organizations']);
  74. $orderTypes = TableRegistry::get('orderTypes', ['schema' => $schema]);
  75. $stuff = TableRegistry::get('stuff', ['schema' => $schema, 'table' => 'things']);
  76. $stuffTypes = TableRegistry::get('stuffTypes', ['schema' => $schema]);
  77. $categories = TableRegistry::get('categories', ['schema' => $schema]);
  78. $table->belongsTo('clients');
  79. $clients->hasOne('orders');
  80. $clients->belongsTo('companies');
  81. $orders->belongsTo('orderTypes');
  82. $orders->hasOne('stuff');
  83. $stuff->belongsTo('stuffTypes');
  84. $companies->belongsTo('categories');
  85. }
  86. /**
  87. * tearDown method
  88. *
  89. * @return void
  90. */
  91. public function tearDown() {
  92. parent::tearDown();
  93. TableRegistry::clear();
  94. }
  95. /**
  96. * Tests that fully defined belongsTo and hasOne relationships are joined correctly
  97. *
  98. * @return void
  99. **/
  100. public function testContainToJoinsOneLevel() {
  101. $contains = [
  102. 'clients' => [
  103. 'orders' => [
  104. 'orderTypes',
  105. 'stuff' => ['stuffTypes']
  106. ],
  107. 'companies' => [
  108. 'foreignKey' => 'organization_id',
  109. 'categories'
  110. ]
  111. ]
  112. ];
  113. $query = $this->getMock('\Cake\ORM\Query', ['join'], [$this->connection, $this->table]);
  114. $query->expects($this->at(0))->method('join')
  115. ->with(['clients' => [
  116. 'table' => 'clients',
  117. 'type' => 'LEFT',
  118. 'conditions' => new QueryExpression([
  119. ['clients.id' => new IdentifierExpression('foo.client_id')]
  120. ])
  121. ]])
  122. ->will($this->returnValue($query));
  123. $query->expects($this->at(1))->method('join')
  124. ->with(['orders' => [
  125. 'table' => 'orders',
  126. 'type' => 'INNER',
  127. 'conditions' => new QueryExpression([
  128. ['clients.id' => new IdentifierExpression('orders.client_id')]
  129. ])
  130. ]])
  131. ->will($this->returnValue($query));
  132. $query->expects($this->at(2))->method('join')
  133. ->with(['orderTypes' => [
  134. 'table' => 'order_types',
  135. 'type' => 'LEFT',
  136. 'conditions' => new QueryExpression([
  137. ['orderTypes.id' => new IdentifierExpression('orders.order_type_id')]
  138. ])
  139. ]])
  140. ->will($this->returnValue($query));
  141. $query->expects($this->at(3))->method('join')
  142. ->with(['stuff' => [
  143. 'table' => 'things',
  144. 'type' => 'INNER',
  145. 'conditions' => new QueryExpression([
  146. ['orders.id' => new IdentifierExpression('stuff.order_id')]
  147. ])
  148. ]])
  149. ->will($this->returnValue($query));
  150. $query->expects($this->at(4))->method('join')
  151. ->with(['stuffTypes' => [
  152. 'table' => 'stuff_types',
  153. 'type' => 'LEFT',
  154. 'conditions' => new QueryExpression([
  155. ['stuffTypes.id' => new IdentifierExpression('stuff.stuff_type_id')]
  156. ])
  157. ]])
  158. ->will($this->returnValue($query));
  159. $query->expects($this->at(5))->method('join')
  160. ->with(['companies' => [
  161. 'table' => 'organizations',
  162. 'type' => 'LEFT',
  163. 'conditions' => new QueryExpression([
  164. ['companies.id' => new IdentifierExpression('clients.organization_id')]
  165. ])
  166. ]])
  167. ->will($this->returnValue($query));
  168. $query->expects($this->at(6))->method('join')
  169. ->with(['categories' => [
  170. 'table' => 'categories',
  171. 'type' => 'LEFT',
  172. 'conditions' => new QueryExpression([
  173. ['categories.id' => new IdentifierExpression('companies.category_id')]
  174. ])
  175. ]])
  176. ->will($this->returnValue($query));
  177. $s = $query
  178. ->select('foo.id')
  179. ->contain($contains)->sql();
  180. }
  181. /**
  182. * Tests setting containments using dot notation, additionally proves that options
  183. * are not overwritten when combining dot notation and array notation
  184. *
  185. * @return void
  186. */
  187. public function testContainDotNotation() {
  188. $query = $this->getMock('\Cake\ORM\Query', ['join'], [$this->connection, $this->table]);
  189. $query->contain([
  190. 'clients.orders.stuff',
  191. 'clients.companies.categories' => ['conditions' => ['a >' => 1]]
  192. ]);
  193. $expected = new \ArrayObject([
  194. 'clients' => [
  195. 'orders' => [
  196. 'stuff' => []
  197. ],
  198. 'companies' => [
  199. 'categories' => [
  200. 'conditions' => ['a >' => 1]
  201. ]
  202. ]
  203. ]
  204. ]);
  205. $this->assertEquals($expected, $query->contain());
  206. $query->contain([
  207. 'clients.orders' => ['fields' => ['a', 'b']],
  208. 'clients' => ['sort' => ['a' => 'desc']],
  209. ]);
  210. $expected['clients']['orders'] += ['fields' => ['a', 'b']];
  211. $expected['clients'] += ['sort' => ['a' => 'desc']];
  212. $this->assertEquals($expected, $query->contain());
  213. }
  214. /**
  215. * Tests that it is possible to pass a function as the array value for contain
  216. *
  217. * @return void
  218. */
  219. public function testContainClosure() {
  220. $builder = function($query) {
  221. };
  222. $query = $this->getMock('\Cake\ORM\Query', ['join'], [$this->connection, $this->table]);
  223. $query->contain([
  224. 'clients.orders.stuff' => ['fields' => ['a']],
  225. 'clients' => $builder
  226. ]);
  227. $expected = new \ArrayObject([
  228. 'clients' => [
  229. 'orders' => [
  230. 'stuff' => ['fields' => ['a']]
  231. ],
  232. 'queryBuilder' => $builder
  233. ]
  234. ]);
  235. $this->assertEquals($expected, $query->contain());
  236. $query = $this->getMock('\Cake\ORM\Query', ['join'], [$this->connection, $this->table]);
  237. $query->contain([
  238. 'clients.orders.stuff' => ['fields' => ['a']],
  239. 'clients' => ['queryBuilder' => $builder]
  240. ]);
  241. $this->assertEquals($expected, $query->contain());
  242. }
  243. /**
  244. * Test that fields for contained models are aliased and added to the select clause
  245. *
  246. * @return void
  247. **/
  248. public function testContainToFieldsPredefined() {
  249. $contains = [
  250. 'clients' => [
  251. 'fields' => ['name', 'company_id', 'clients.telephone'],
  252. 'orders' => [
  253. 'fields' => ['total', 'placed']
  254. ]
  255. ]
  256. ];
  257. $table = TableRegistry::get('foo');
  258. $query = new Query($this->connection, $table);
  259. $query->select('foo.id')->contain($contains)->sql();
  260. $select = $query->clause('select');
  261. $expected = [
  262. 'foo__id' => 'foo.id', 'clients__name' => 'clients.name',
  263. 'clients__company_id' => 'clients.company_id',
  264. 'clients__telephone' => 'clients.telephone',
  265. 'orders__total' => 'orders.total', 'orders__placed' => 'orders.placed'
  266. ];
  267. $expected = $this->_quoteArray($expected);
  268. $this->assertEquals($expected, $select);
  269. }
  270. /**
  271. * Tests that default fields for associations are added to the select clause when
  272. * none is specified
  273. *
  274. * @return void
  275. **/
  276. public function testContainToFieldsDefault() {
  277. $contains = ['clients' => ['orders']];
  278. $query = new Query($this->connection, $this->table);
  279. $query->select()->contain($contains)->sql();
  280. $select = $query->clause('select');
  281. $expected = [
  282. 'foo__id' => 'foo.id', 'clients__name' => 'clients.name',
  283. 'clients__id' => 'clients.id', 'clients__phone' => 'clients.phone',
  284. 'orders__id' => 'orders.id', 'orders__total' => 'orders.total',
  285. 'orders__placed' => 'orders.placed'
  286. ];
  287. $expected = $this->_quoteArray($expected);
  288. $this->assertEquals($expected, $select);
  289. $contains['clients']['fields'] = ['name'];
  290. $query = new Query($this->connection, $this->table);
  291. $query->select('foo.id')->contain($contains)->sql();
  292. $select = $query->clause('select');
  293. $expected = ['foo__id' => 'foo.id', 'clients__name' => 'clients.name'];
  294. $expected = $this->_quoteArray($expected);
  295. $this->assertEquals($expected, $select);
  296. $contains['clients']['fields'] = [];
  297. $contains['clients']['orders']['fields'] = false;
  298. $query = new Query($this->connection, $this->table);
  299. $query->select()->contain($contains)->sql();
  300. $select = $query->clause('select');
  301. $expected = [
  302. 'foo__id' => 'foo.id',
  303. 'clients__id' => 'clients.id',
  304. 'clients__name' => 'clients.name',
  305. 'clients__phone' => 'clients.phone',
  306. ];
  307. $expected = $this->_quoteArray($expected);
  308. $this->assertEquals($expected, $select);
  309. }
  310. /**
  311. * Helper function sued to quoted both keys and values in an array in case
  312. * the test suite is running with auto quoting enabled
  313. *
  314. * @param array $elements
  315. * @return array
  316. */
  317. protected function _quoteArray($elements) {
  318. if ($this->connection->driver()->autoQuoting()) {
  319. $quoter = function($e) {
  320. return $this->connection->driver()->quoteIdentifier($e);
  321. };
  322. return array_combine(
  323. array_map($quoter, array_keys($elements)),
  324. array_map($quoter, array_values($elements))
  325. );
  326. }
  327. return $elements;
  328. }
  329. /**
  330. * Tests that results are grouped correctly when using contain()
  331. * and results are not hydrated
  332. *
  333. * @return void
  334. */
  335. public function testContainResultFetchingOneLevel() {
  336. $table = TableRegistry::get('articles', ['table' => 'articles']);
  337. $table->belongsTo('authors');
  338. $query = new Query($this->connection, $table);
  339. $results = $query->select()
  340. ->contain('authors')
  341. ->hydrate(false)
  342. ->order(['articles.id' => 'asc'])
  343. ->toArray();
  344. $expected = [
  345. [
  346. 'id' => 1,
  347. 'title' => 'First Article',
  348. 'body' => 'First Article Body',
  349. 'author_id' => 1,
  350. 'published' => 'Y',
  351. 'author' => [
  352. 'id' => 1,
  353. 'name' => 'mariano'
  354. ]
  355. ],
  356. [
  357. 'id' => 2,
  358. 'title' => 'Second Article',
  359. 'body' => 'Second Article Body',
  360. 'author_id' => 3,
  361. 'published' => 'Y',
  362. 'author' => [
  363. 'id' => 3,
  364. 'name' => 'larry'
  365. ]
  366. ],
  367. [
  368. 'id' => 3,
  369. 'title' => 'Third Article',
  370. 'body' => 'Third Article Body',
  371. 'author_id' => 1,
  372. 'published' => 'Y',
  373. 'author' => [
  374. 'id' => 1,
  375. 'name' => 'mariano'
  376. ]
  377. ],
  378. ];
  379. $this->assertEquals($expected, $results);
  380. }
  381. /**
  382. * Data provider for the two types of strategies HasMany implements
  383. *
  384. * @return void
  385. */
  386. public function strategiesProvider() {
  387. return [['subquery'], ['select']];
  388. }
  389. /**
  390. * Tests that HasMany associations are correctly eager loaded and results
  391. * correctly nested when no hydration is used
  392. * Also that the query object passes the correct parent model keys to the
  393. * association objects in order to perform eager loading with select strategy
  394. *
  395. * @dataProvider strategiesProvider
  396. * @return void
  397. */
  398. public function testHasManyEagerLoadingNoHydration($strategy) {
  399. $table = TableRegistry::get('authors');
  400. TableRegistry::get('articles');
  401. $table->hasMany('articles', [
  402. 'property' => 'articles',
  403. 'strategy' => $strategy,
  404. 'sort' => ['articles.id' => 'asc']
  405. ]);
  406. $query = new Query($this->connection, $table);
  407. $results = $query->select()
  408. ->contain('articles')
  409. ->hydrate(false)
  410. ->toArray();
  411. $expected = [
  412. [
  413. 'id' => 1,
  414. 'name' => 'mariano',
  415. 'articles' => [
  416. [
  417. 'id' => 1,
  418. 'title' => 'First Article',
  419. 'body' => 'First Article Body',
  420. 'author_id' => 1,
  421. 'published' => 'Y',
  422. ],
  423. [
  424. 'id' => 3,
  425. 'title' => 'Third Article',
  426. 'body' => 'Third Article Body',
  427. 'author_id' => 1,
  428. 'published' => 'Y',
  429. ],
  430. ]
  431. ],
  432. [
  433. 'id' => 2,
  434. 'name' => 'nate',
  435. ],
  436. [
  437. 'id' => 3,
  438. 'name' => 'larry',
  439. 'articles' => [
  440. [
  441. 'id' => 2,
  442. 'title' => 'Second Article',
  443. 'body' => 'Second Article Body',
  444. 'author_id' => 3,
  445. 'published' => 'Y'
  446. ]
  447. ]
  448. ],
  449. [
  450. 'id' => 4,
  451. 'name' => 'garrett',
  452. ]
  453. ];
  454. $this->assertEquals($expected, $results);
  455. $results = $query->repository($table)
  456. ->select()
  457. ->contain(['articles' => ['conditions' => ['id' => 2]]])
  458. ->hydrate(false)
  459. ->toArray();
  460. unset($expected[0]['articles']);
  461. $this->assertEquals($expected, $results);
  462. $this->assertEquals($table->association('articles')->strategy(), $strategy);
  463. }
  464. /**
  465. * Tests that it is possible to set fields & order in a hasMany result set
  466. *
  467. * @dataProvider strategiesProvider
  468. * @return void
  469. **/
  470. public function testHasManyEagerLoadingFieldsAndOrderNoHydration($strategy) {
  471. $table = TableRegistry::get('authors');
  472. TableRegistry::get('articles');
  473. $table->hasMany('articles', ['property' => 'articles'] + compact('strategy'));
  474. $query = new Query($this->connection, $table);
  475. $results = $query->select()
  476. ->contain([
  477. 'articles' => [
  478. 'fields' => ['title', 'author_id'],
  479. 'sort' => ['id' => 'DESC']
  480. ]
  481. ])
  482. ->hydrate(false)
  483. ->toArray();
  484. $expected = [
  485. [
  486. 'id' => 1,
  487. 'name' => 'mariano',
  488. 'articles' => [
  489. ['title' => 'Third Article', 'author_id' => 1],
  490. ['title' => 'First Article', 'author_id' => 1],
  491. ]
  492. ],
  493. [
  494. 'id' => 2,
  495. 'name' => 'nate',
  496. ],
  497. [
  498. 'id' => 3,
  499. 'name' => 'larry',
  500. 'articles' => [
  501. ['title' => 'Second Article', 'author_id' => 3],
  502. ]
  503. ],
  504. [
  505. 'id' => 4,
  506. 'name' => 'garrett',
  507. ],
  508. ];
  509. $this->assertEquals($expected, $results);
  510. }
  511. /**
  512. * Tests that deep associations can be eagerly loaded
  513. *
  514. * @dataProvider strategiesProvider
  515. * @return void
  516. */
  517. public function testHasManyEagerLoadingDeep($strategy) {
  518. $table = TableRegistry::get('authors');
  519. $article = TableRegistry::get('articles');
  520. $table->hasMany('articles', [
  521. 'property' => 'articles',
  522. 'stratgey' => $strategy,
  523. 'sort' => ['articles.id' => 'asc']
  524. ]);
  525. $article->belongsTo('authors');
  526. $query = new Query($this->connection, $table);
  527. $results = $query->select()
  528. ->contain(['articles' => ['authors']])
  529. ->hydrate(false)
  530. ->toArray();
  531. $expected = [
  532. [
  533. 'id' => 1,
  534. 'name' => 'mariano',
  535. 'articles' => [
  536. [
  537. 'id' => 1,
  538. 'title' => 'First Article',
  539. 'author_id' => 1,
  540. 'body' => 'First Article Body',
  541. 'published' => 'Y',
  542. 'author' => ['id' => 1, 'name' => 'mariano']
  543. ],
  544. [
  545. 'id' => 3,
  546. 'title' => 'Third Article',
  547. 'author_id' => 1,
  548. 'body' => 'Third Article Body',
  549. 'published' => 'Y',
  550. 'author' => ['id' => 1, 'name' => 'mariano']
  551. ],
  552. ]
  553. ],
  554. [
  555. 'id' => 2,
  556. 'name' => 'nate'
  557. ],
  558. [
  559. 'id' => 3,
  560. 'name' => 'larry',
  561. 'articles' => [
  562. [
  563. 'id' => 2,
  564. 'title' => 'Second Article',
  565. 'author_id' => 3,
  566. 'body' => 'Second Article Body',
  567. 'published' => 'Y',
  568. 'author' => ['id' => 3, 'name' => 'larry']
  569. ],
  570. ]
  571. ],
  572. [
  573. 'id' => 4,
  574. 'name' => 'garrett'
  575. ]
  576. ];
  577. $this->assertEquals($expected, $results);
  578. }
  579. /**
  580. * Tests that hasMany associations can be loaded even when related to a secondary
  581. * model in the query
  582. *
  583. * @dataProvider strategiesProvider
  584. * @return void
  585. */
  586. public function testHasManyEagerLoadingFromSecondaryTable($strategy) {
  587. $author = TableRegistry::get('authors');
  588. $article = TableRegistry::get('articles');
  589. $post = TableRegistry::get('posts');
  590. $author->hasMany('posts', compact('strategy'));
  591. $article->belongsTo('authors');
  592. $query = new Query($this->connection, $article);
  593. $results = $query->select()
  594. ->contain(['authors' => ['posts']])
  595. ->order(['articles.id' => 'ASC'])
  596. ->hydrate(false)
  597. ->toArray();
  598. $expected = [
  599. [
  600. 'id' => 1,
  601. 'title' => 'First Article',
  602. 'body' => 'First Article Body',
  603. 'author_id' => 1,
  604. 'published' => 'Y',
  605. 'author' => [
  606. 'id' => 1,
  607. 'name' => 'mariano',
  608. 'posts' => [
  609. [
  610. 'id' => '1',
  611. 'title' => 'First Post',
  612. 'body' => 'First Post Body',
  613. 'author_id' => 1,
  614. 'published' => 'Y',
  615. ],
  616. [
  617. 'id' => '3',
  618. 'title' => 'Third Post',
  619. 'body' => 'Third Post Body',
  620. 'author_id' => 1,
  621. 'published' => 'Y',
  622. ],
  623. ]
  624. ]
  625. ],
  626. [
  627. 'id' => 2,
  628. 'title' => 'Second Article',
  629. 'body' => 'Second Article Body',
  630. 'author_id' => 3,
  631. 'published' => 'Y',
  632. 'author' => [
  633. 'id' => 3,
  634. 'name' => 'larry',
  635. 'posts' => [
  636. [
  637. 'id' => 2,
  638. 'title' => 'Second Post',
  639. 'body' => 'Second Post Body',
  640. 'author_id' => 3,
  641. 'published' => 'Y',
  642. ]
  643. ]
  644. ]
  645. ],
  646. [
  647. 'id' => 3,
  648. 'title' => 'Third Article',
  649. 'body' => 'Third Article Body',
  650. 'author_id' => 1,
  651. 'published' => 'Y',
  652. 'author' => [
  653. 'id' => 1,
  654. 'name' => 'mariano',
  655. 'posts' => [
  656. [
  657. 'id' => '1',
  658. 'title' => 'First Post',
  659. 'body' => 'First Post Body',
  660. 'author_id' => 1,
  661. 'published' => 'Y',
  662. ],
  663. [
  664. 'id' => '3',
  665. 'title' => 'Third Post',
  666. 'body' => 'Third Post Body',
  667. 'author_id' => 1,
  668. 'published' => 'Y',
  669. ],
  670. ]
  671. ]
  672. ],
  673. ];
  674. $this->assertEquals($expected, $results);
  675. }
  676. /**
  677. * Tests that BelongsToMany associations are correctly eager loaded.
  678. * Also that the query object passes the correct parent model keys to the
  679. * association objects in order to perform eager loading with select strategy
  680. *
  681. * @dataProvider strategiesProvider
  682. * @return void
  683. **/
  684. public function testBelongsToManyEagerLoadingNoHydration($strategy) {
  685. $table = TableRegistry::get('Articles');
  686. TableRegistry::get('Tags');
  687. TableRegistry::get('ArticlesTags', [
  688. 'table' => 'articles_tags'
  689. ]);
  690. $table->belongsToMany('Tags', ['strategy' => $strategy]);
  691. $query = new Query($this->connection, $table);
  692. $results = $query->select()->contain('Tags')->hydrate(false)->toArray();
  693. $expected = [
  694. [
  695. 'id' => 1,
  696. 'author_id' => 1,
  697. 'title' => 'First Article',
  698. 'body' => 'First Article Body',
  699. 'published' => 'Y',
  700. 'tags' => [
  701. [
  702. 'id' => 1,
  703. 'name' => 'tag1',
  704. '_joinData' => ['article_id' => 1, 'tag_id' => 1]
  705. ],
  706. [
  707. 'id' => 2,
  708. 'name' => 'tag2',
  709. '_joinData' => ['article_id' => 1, 'tag_id' => 2]
  710. ]
  711. ]
  712. ],
  713. [
  714. 'id' => 2,
  715. 'title' => 'Second Article',
  716. 'body' => 'Second Article Body',
  717. 'author_id' => 3,
  718. 'published' => 'Y',
  719. 'tags' => [
  720. [
  721. 'id' => 1,
  722. 'name' => 'tag1',
  723. '_joinData' => ['article_id' => 2, 'tag_id' => 1]
  724. ],
  725. [
  726. 'id' => 3,
  727. 'name' => 'tag3',
  728. '_joinData' => ['article_id' => 2, 'tag_id' => 3]
  729. ]
  730. ]
  731. ],
  732. [
  733. 'id' => 3,
  734. 'title' => 'Third Article',
  735. 'body' => 'Third Article Body',
  736. 'author_id' => 1,
  737. 'published' => 'Y',
  738. ],
  739. ];
  740. $this->assertEquals($expected, $results);
  741. $results = $query->select()
  742. ->contain(['Tags' => ['conditions' => ['id' => 3]]])
  743. ->hydrate(false)
  744. ->toArray();
  745. $expected = [
  746. [
  747. 'id' => 1,
  748. 'author_id' => 1,
  749. 'title' => 'First Article',
  750. 'body' => 'First Article Body',
  751. 'published' => 'Y',
  752. ],
  753. [
  754. 'id' => 2,
  755. 'title' => 'Second Article',
  756. 'body' => 'Second Article Body',
  757. 'author_id' => 3,
  758. 'published' => 'Y',
  759. 'tags' => [
  760. [
  761. 'id' => 3,
  762. 'name' => 'tag3',
  763. '_joinData' => ['article_id' => 2, 'tag_id' => 3]
  764. ]
  765. ]
  766. ],
  767. [
  768. 'id' => 3,
  769. 'title' => 'Third Article',
  770. 'body' => 'Third Article Body',
  771. 'author_id' => 1,
  772. 'published' => 'Y',
  773. ],
  774. ];
  775. $this->assertEquals($expected, $results);
  776. $this->assertEquals($table->association('Tags')->strategy(), $strategy);
  777. }
  778. /**
  779. * Tests that tables results can be filtered by the result of a HasMany
  780. *
  781. * @return void
  782. */
  783. public function testFilteringByHasManyNoHydration() {
  784. $query = new Query($this->connection, $this->table);
  785. $table = TableRegistry::get('authors');
  786. TableRegistry::get('articles');
  787. $table->hasMany('articles');
  788. $results = $query->repository($table)
  789. ->select()
  790. ->hydrate(false)
  791. ->matching('articles', function($q) {
  792. return $q->where(['articles.id' => 2]);
  793. })
  794. ->toArray();
  795. $expected = [
  796. [
  797. 'id' => 3,
  798. 'name' => 'larry',
  799. 'articles' => [
  800. 'id' => 2,
  801. 'title' => 'Second Article',
  802. 'body' => 'Second Article Body',
  803. 'author_id' => 3,
  804. 'published' => 'Y',
  805. ]
  806. ]
  807. ];
  808. $this->assertEquals($expected, $results);
  809. }
  810. /**
  811. * Tests that BelongsToMany associations are correctly eager loaded.
  812. * Also that the query object passes the correct parent model keys to the
  813. * association objects in order to perform eager loading with select strategy
  814. *
  815. * @return void
  816. **/
  817. public function testFilteringByBelongsToManyNoHydration() {
  818. $query = new Query($this->connection, $this->table);
  819. $table = TableRegistry::get('Articles');
  820. TableRegistry::get('Tags');
  821. TableRegistry::get('ArticlesTags', [
  822. 'table' => 'articles_tags'
  823. ]);
  824. $table->belongsToMany('Tags');
  825. $results = $query->repository($table)->select()
  826. ->matching('Tags', function($q) {
  827. return $q->where(['Tags.id' => 3]);
  828. })
  829. ->hydrate(false)
  830. ->toArray();
  831. $expected = [
  832. [
  833. 'id' => 2,
  834. 'author_id' => 3,
  835. 'title' => 'Second Article',
  836. 'body' => 'Second Article Body',
  837. 'published' => 'Y',
  838. 'tags' => [
  839. 'id' => 3,
  840. 'name' => 'tag3'
  841. ]
  842. ]
  843. ];
  844. $this->assertEquals($expected, $results);
  845. $query = new Query($this->connection, $table);
  846. $results = $query->select()
  847. ->matching('Tags', function($q) {
  848. return $q->where(['Tags.name' => 'tag2']);
  849. })
  850. ->hydrate(false)
  851. ->toArray();
  852. $expected = [
  853. [
  854. 'id' => 1,
  855. 'title' => 'First Article',
  856. 'body' => 'First Article Body',
  857. 'author_id' => 1,
  858. 'published' => 'Y',
  859. 'tags' => [
  860. 'id' => 2,
  861. 'name' => 'tag2'
  862. ]
  863. ]
  864. ];
  865. $this->assertEquals($expected, $results);
  866. }
  867. /**
  868. * Tests that it is possible to filter by deep associations
  869. *
  870. * @return void
  871. */
  872. public function testMatchingDotNotation() {
  873. $query = new Query($this->connection, $this->table);
  874. $table = TableRegistry::get('authors');
  875. TableRegistry::get('articles');
  876. $table->hasMany('articles');
  877. TableRegistry::get('articles')->belongsToMany('tags');
  878. $results = $query->repository($table)
  879. ->select()
  880. ->hydrate(false)
  881. ->matching('articles.tags', function($q) {
  882. return $q->where(['tags.id' => 2]);
  883. })
  884. ->toArray();
  885. $expected = [
  886. [
  887. 'id' => 1,
  888. 'name' => 'mariano',
  889. 'articles' => [
  890. 'id' => 1,
  891. 'title' => 'First Article',
  892. 'body' => 'First Article Body',
  893. 'author_id' => 1,
  894. 'published' => 'Y',
  895. 'tags' => [
  896. 'id' => 2,
  897. 'name' => 'tag2'
  898. ]
  899. ]
  900. ]
  901. ];
  902. $this->assertEquals($expected, $results);
  903. }
  904. /**
  905. * Test setResult()
  906. *
  907. * @return void
  908. */
  909. public function testSetResult() {
  910. $query = new Query($this->connection, $this->table);
  911. $stmt = $this->getMock('Cake\Database\StatementInterface');
  912. $results = new ResultSet($query, $stmt);
  913. $query->setResult($results);
  914. $this->assertSame($results, $query->all());
  915. }
  916. /**
  917. * Tests that applying array options to a query will convert them
  918. * to equivalent function calls with the correspondent array values
  919. *
  920. * @return void
  921. */
  922. public function testApplyOptions() {
  923. $options = [
  924. 'fields' => ['field_a', 'field_b'],
  925. 'conditions' => ['field_a' => 1, 'field_b' => 'something'],
  926. 'limit' => 1,
  927. 'order' => ['a' => 'ASC'],
  928. 'offset' => 5,
  929. 'group' => ['field_a'],
  930. 'having' => ['field_a >' => 100],
  931. 'contain' => ['table_a' => ['table_b']],
  932. 'join' => ['table_a' => ['conditions' => ['a > b']]]
  933. ];
  934. $query = new Query($this->connection, $this->table);
  935. $query->applyOptions($options);
  936. $this->assertEquals(['field_a', 'field_b'], $query->clause('select'));
  937. $expected = new QueryExpression($options['conditions']);
  938. $result = $query->clause('where');
  939. $this->assertEquals($expected, $result);
  940. $this->assertEquals(1, $query->clause('limit'));
  941. $expected = new QueryExpression(['a > b']);
  942. $result = $query->clause('join');
  943. $this->assertEquals([
  944. ['alias' => 'table_a', 'type' => 'INNER', 'conditions' => $expected]
  945. ], $result);
  946. $expected = new OrderByExpression(['a' => 'ASC']);
  947. $this->assertEquals($expected, $query->clause('order'));
  948. $this->assertEquals(5, $query->clause('offset'));
  949. $this->assertEquals(['field_a'], $query->clause('group'));
  950. $expected = new QueryExpression($options['having']);
  951. $this->assertEquals($expected, $query->clause('having'));
  952. $expected = new \ArrayObject(['table_a' => ['table_b' => []]]);
  953. $this->assertEquals($expected, $query->contain());
  954. }
  955. /**
  956. * ApplyOptions should ignore null values.
  957. *
  958. * @return void
  959. */
  960. public function testApplyOptionsIgnoreNull() {
  961. $options = [
  962. 'fields' => null,
  963. ];
  964. $query = new Query($this->connection, $this->table);
  965. $query->applyOptions($options);
  966. $this->assertEquals([], $query->clause('select'));
  967. }
  968. /**
  969. * Tests getOptions() method
  970. *
  971. * @return void
  972. */
  973. public function testGetOptions() {
  974. $options = ['doABarrelRoll' => true, 'fields' => ['id', 'name']];
  975. $query = new Query($this->connection, $this->table);
  976. $query->applyOptions($options);
  977. $expected = ['doABarrelRoll' => true];
  978. $this->assertEquals($expected, $query->getOptions());
  979. $expected = ['doABarrelRoll' => false, 'doAwesome' => true];
  980. $query->applyOptions($expected);
  981. $this->assertEquals($expected, $query->getOptions());
  982. }
  983. /**
  984. * Tests registering mappers with mapReduce()
  985. *
  986. * @return void
  987. */
  988. public function testMapReduceOnlyMapper() {
  989. $mapper1 = function() {
  990. };
  991. $mapper2 = function() {
  992. };
  993. $query = new Query($this->connection, $this->table);
  994. $this->assertSame($query, $query->mapReduce($mapper1));
  995. $this->assertEquals(
  996. [['mapper' => $mapper1, 'reducer' => null]],
  997. $query->mapReduce()
  998. );
  999. $this->assertEquals($query, $query->mapReduce($mapper1));
  1000. $result = $query->mapReduce();
  1001. $this->assertEquals(
  1002. [
  1003. ['mapper' => $mapper1, 'reducer' => null],
  1004. ['mapper' => $mapper2, 'reducer' => null]
  1005. ],
  1006. $result
  1007. );
  1008. }
  1009. /**
  1010. * Tests registering mappers and reducers with mapReduce()
  1011. *
  1012. * @return void
  1013. */
  1014. public function testMapReduceBothMethods() {
  1015. $mapper1 = function() {
  1016. };
  1017. $mapper2 = function() {
  1018. };
  1019. $reducer1 = function() {
  1020. };
  1021. $reducer2 = function() {
  1022. };
  1023. $query = new Query($this->connection, $this->table);
  1024. $this->assertSame($query, $query->mapReduce($mapper1, $reducer1));
  1025. $this->assertEquals(
  1026. [['mapper' => $mapper1, 'reducer' => $reducer1]],
  1027. $query->mapReduce()
  1028. );
  1029. $this->assertSame($query, $query->mapReduce($mapper2, $reducer2));
  1030. $this->assertEquals(
  1031. [
  1032. ['mapper' => $mapper1, 'reducer' => $reducer1],
  1033. ['mapper' => $mapper2, 'reducer' => $reducer2]
  1034. ],
  1035. $query->mapReduce()
  1036. );
  1037. }
  1038. /**
  1039. * Tests that it is possible to overwrite previous map reducers
  1040. *
  1041. * @return void
  1042. */
  1043. public function testOverwriteMapReduce() {
  1044. $mapper1 = function() {
  1045. };
  1046. $mapper2 = function() {
  1047. };
  1048. $reducer1 = function() {
  1049. };
  1050. $reducer2 = function() {
  1051. };
  1052. $query = new Query($this->connection, $this->table);
  1053. $this->assertEquals($query, $query->mapReduce($mapper1, $reducer1));
  1054. $this->assertEquals(
  1055. [['mapper' => $mapper1, 'reducer' => $reducer1]],
  1056. $query->mapReduce()
  1057. );
  1058. $this->assertEquals($query, $query->mapReduce($mapper2, $reducer2, true));
  1059. $this->assertEquals(
  1060. [['mapper' => $mapper2, 'reducer' => $reducer2]],
  1061. $query->mapReduce()
  1062. );
  1063. }
  1064. /**
  1065. * Tests that multiple map reducers can be stacked
  1066. *
  1067. * @return void
  1068. */
  1069. public function testResultsAreWrappedInMapReduce() {
  1070. $params = [$this->connection, $this->table];
  1071. $query = $this->getMock('\Cake\ORM\Query', ['execute'], $params);
  1072. $statement = $this->getMock('\Database\StatementInterface', ['fetch', 'closeCursor']);
  1073. $statement->expects($this->exactly(3))
  1074. ->method('fetch')
  1075. ->will($this->onConsecutiveCalls(['a' => 1], ['a' => 2], false));
  1076. $query->expects($this->once())
  1077. ->method('execute')
  1078. ->will($this->returnValue($statement));
  1079. $query->mapReduce(function($v, $k, $mr) {
  1080. $mr->emit($v['a']);
  1081. });
  1082. $query->mapReduce(
  1083. function($v, $k, $mr) {
  1084. $mr->emitIntermediate($v, $k);
  1085. },
  1086. function($v, $k, $mr) {
  1087. $mr->emit($v[0] + 1);
  1088. }
  1089. );
  1090. $this->assertEquals([2, 3], iterator_to_array($query->all()));
  1091. }
  1092. /**
  1093. * Tests first() method when the query has not been executed before
  1094. *
  1095. * @return void
  1096. */
  1097. public function testFirstDirtyQuery() {
  1098. $table = TableRegistry::get('articles', ['table' => 'articles']);
  1099. $query = new Query($this->connection, $table);
  1100. $result = $query->select(['id'])->hydrate(false)->first();
  1101. $this->assertEquals(['id' => 1], $result);
  1102. $this->assertEquals(1, $query->clause('limit'));
  1103. $result = $query->select(['id'])->first();
  1104. $this->assertEquals(['id' => 1], $result);
  1105. }
  1106. /**
  1107. * Tests that first can be called again on an already executed query
  1108. *
  1109. * @return void
  1110. */
  1111. public function testFirstCleanQuery() {
  1112. $table = TableRegistry::get('articles', ['table' => 'articles']);
  1113. $query = new Query($this->connection, $table);
  1114. $query->select(['id'])->toArray();
  1115. $first = $query->hydrate(false)->first();
  1116. $this->assertEquals(['id' => 1], $first);
  1117. $this->assertEquals(1, $query->clause('limit'));
  1118. }
  1119. /**
  1120. * Tests that first() will not execute the same query twice
  1121. *
  1122. * @return void
  1123. */
  1124. public function testFirstSameResult() {
  1125. $table = TableRegistry::get('articles', ['table' => 'articles']);
  1126. $query = new Query($this->connection, $table);
  1127. $query->select(['id'])->toArray();
  1128. $first = $query->hydrate(false)->first();
  1129. $resultSet = $query->all();
  1130. $this->assertEquals(['id' => 1], $first);
  1131. $this->assertSame($resultSet, $query->all());
  1132. }
  1133. /**
  1134. * Tests that first can be called against a query with a mapReduce
  1135. *
  1136. * @return void
  1137. */
  1138. public function testFirstMapReduce() {
  1139. $map = function($row, $key, $mapReduce) {
  1140. $mapReduce->emitIntermediate($row['id'], 'id');
  1141. };
  1142. $reduce = function($values, $key, $mapReduce) {
  1143. $mapReduce->emit(array_sum($values));
  1144. };
  1145. $table = TableRegistry::get('articles', ['table' => 'articles']);
  1146. $query = new Query($this->connection, $table);
  1147. $query->select(['id'])
  1148. ->hydrate(false)
  1149. ->mapReduce($map, $reduce);
  1150. $first = $query->first();
  1151. $this->assertEquals(1, $first);
  1152. }
  1153. /**
  1154. * Testing hydrating a result set into Entity objects
  1155. *
  1156. * @return void
  1157. */
  1158. public function testHydrateSimple() {
  1159. $table = TableRegistry::get('articles', ['table' => 'articles']);
  1160. $query = new Query($this->connection, $table);
  1161. $results = $query->select()->toArray();
  1162. $this->assertCount(3, $results);
  1163. foreach ($results as $r) {
  1164. $this->assertInstanceOf('\Cake\ORM\Entity', $r);
  1165. }
  1166. $first = $results[0];
  1167. $this->assertEquals(1, $first->id);
  1168. $this->assertEquals(1, $first->author_id);
  1169. $this->assertEquals('First Article', $first->title);
  1170. $this->assertEquals('First Article Body', $first->body);
  1171. $this->assertEquals('Y', $first->published);
  1172. }
  1173. /**
  1174. * Tests that has many results are also hydrated correctly
  1175. *
  1176. * @return void
  1177. */
  1178. public function testHydrateWithHasMany() {
  1179. $table = TableRegistry::get('authors');
  1180. TableRegistry::get('articles');
  1181. $table->hasMany('articles', [
  1182. 'property' => 'articles',
  1183. 'sort' => ['articles.id' => 'asc']
  1184. ]);
  1185. $query = new Query($this->connection, $table);
  1186. $results = $query->select()
  1187. ->contain('articles')
  1188. ->toArray();
  1189. $first = $results[0];
  1190. foreach ($first->articles as $r) {
  1191. $this->assertInstanceOf('\Cake\ORM\Entity', $r);
  1192. }
  1193. $this->assertCount(2, $first->articles);
  1194. $expected = [
  1195. 'id' => 1,
  1196. 'title' => 'First Article',
  1197. 'body' => 'First Article Body',
  1198. 'author_id' => 1,
  1199. 'published' => 'Y',
  1200. ];
  1201. $this->assertEquals($expected, $first->articles[0]->toArray());
  1202. $expected = [
  1203. 'id' => 3,
  1204. 'title' => 'Third Article',
  1205. 'author_id' => 1,
  1206. 'body' => 'Third Article Body',
  1207. 'published' => 'Y',
  1208. ];
  1209. $this->assertEquals($expected, $first->articles[1]->toArray());
  1210. }
  1211. /**
  1212. * Tests that belongsToMany associations are also correctly hydrated
  1213. *
  1214. * @return void
  1215. */
  1216. public function testHydrateBelongsToMany() {
  1217. $table = TableRegistry::get('Articles');
  1218. TableRegistry::get('Tags');
  1219. TableRegistry::get('ArticlesTags', [
  1220. 'table' => 'articles_tags'
  1221. ]);
  1222. $table->belongsToMany('Tags');
  1223. $query = new Query($this->connection, $table);
  1224. $results = $query
  1225. ->select()
  1226. ->contain('Tags')
  1227. ->toArray();
  1228. $first = $results[0];
  1229. foreach ($first->tags as $r) {
  1230. $this->assertInstanceOf('\Cake\ORM\Entity', $r);
  1231. }
  1232. $this->assertCount(2, $first->tags);
  1233. $expected = [
  1234. 'id' => 1,
  1235. 'name' => 'tag1',
  1236. '_joinData' => ['article_id' => 1, 'tag_id' => 1]
  1237. ];
  1238. $this->assertEquals($expected, $first->tags[0]->toArray());
  1239. $expected = [
  1240. 'id' => 2,
  1241. 'name' => 'tag2',
  1242. '_joinData' => ['article_id' => 1, 'tag_id' => 2]
  1243. ];
  1244. $this->assertEquals($expected, $first->tags[1]->toArray());
  1245. }
  1246. /**
  1247. * Tests that belongsTo relations are correctly hydrated
  1248. *
  1249. * @return void
  1250. */
  1251. public function testHydrateBelongsTo() {
  1252. $table = TableRegistry::get('articles');
  1253. TableRegistry::get('authors');
  1254. $table->belongsTo('authors');
  1255. $query = new Query($this->connection, $table);
  1256. $results = $query->select()
  1257. ->contain('authors')
  1258. ->order(['articles.id' => 'asc'])
  1259. ->toArray();
  1260. $this->assertCount(3, $results);
  1261. $first = $results[0];
  1262. $this->assertInstanceOf('\Cake\ORM\Entity', $first->author);
  1263. $expected = ['id' => 1, 'name' => 'mariano'];
  1264. $this->assertEquals($expected, $first->author->toArray());
  1265. }
  1266. /**
  1267. * Tests that deeply nested associations are also hydrated correctly
  1268. *
  1269. * @return void
  1270. */
  1271. public function testHydrateDeep() {
  1272. $table = TableRegistry::get('authors');
  1273. $article = TableRegistry::get('articles');
  1274. $table->hasMany('articles', [
  1275. 'property' => 'articles',
  1276. 'sort' => ['articles.id' => 'asc']
  1277. ]);
  1278. $article->belongsTo('authors');
  1279. $query = new Query($this->connection, $table);
  1280. $results = $query->select()
  1281. ->contain(['articles' => ['authors']])
  1282. ->toArray();
  1283. $this->assertCount(4, $results);
  1284. $first = $results[0];
  1285. $this->assertInstanceOf('\Cake\ORM\Entity', $first->articles[0]->author);
  1286. $expected = ['id' => 1, 'name' => 'mariano'];
  1287. $this->assertEquals($expected, $first->articles[0]->author->toArray());
  1288. $this->assertFalse(isset($results[3]->articles));
  1289. }
  1290. /**
  1291. * Tests that it is possible to use a custom entity class
  1292. *
  1293. * @return void
  1294. */
  1295. public function testHydrateCustomObject() {
  1296. $class = $this->getMockClass('\Cake\ORM\Entity', ['fakeMethod']);
  1297. $table = TableRegistry::get('articles', [
  1298. 'table' => 'articles',
  1299. 'entityClass' => '\\' . $class
  1300. ]);
  1301. $query = new Query($this->connection, $table);
  1302. $results = $query->select()->toArray();
  1303. $this->assertCount(3, $results);
  1304. foreach ($results as $r) {
  1305. $this->assertInstanceOf($class, $r);
  1306. }
  1307. $first = $results[0];
  1308. $this->assertEquals(1, $first->id);
  1309. $this->assertEquals(1, $first->author_id);
  1310. $this->assertEquals('First Article', $first->title);
  1311. $this->assertEquals('First Article Body', $first->body);
  1312. $this->assertEquals('Y', $first->published);
  1313. }
  1314. /**
  1315. * Tests that has many results are also hydrated correctly
  1316. * when specified a custom entity class
  1317. *
  1318. * @return void
  1319. */
  1320. public function testHydrateWithHasManyCustomEntity() {
  1321. $authorEntity = $this->getMockClass('\Cake\ORM\Entity', ['foo']);
  1322. $articleEntity = $this->getMockClass('\Cake\ORM\Entity', ['foo']);
  1323. $table = TableRegistry::get('authors', [
  1324. 'entityClass' => '\\' . $authorEntity
  1325. ]);
  1326. TableRegistry::get('articles', [
  1327. 'entityClass' => '\\' . $articleEntity
  1328. ]);
  1329. $table->hasMany('articles', [
  1330. 'property' => 'articles',
  1331. 'sort' => ['articles.id' => 'asc']
  1332. ]);
  1333. $query = new Query($this->connection, $table);
  1334. $results = $query->select()
  1335. ->contain('articles')
  1336. ->toArray();
  1337. $first = $results[0];
  1338. $this->assertInstanceOf($authorEntity, $first);
  1339. foreach ($first->articles as $r) {
  1340. $this->assertInstanceOf($articleEntity, $r);
  1341. }
  1342. $this->assertCount(2, $first->articles);
  1343. $expected = [
  1344. 'id' => 1,
  1345. 'title' => 'First Article',
  1346. 'body' => 'First Article Body',
  1347. 'author_id' => 1,
  1348. 'published' => 'Y',
  1349. ];
  1350. $this->assertEquals($expected, $first->articles[0]->toArray());
  1351. }
  1352. /**
  1353. * Tests that belongsTo relations are correctly hydrated into a custom entity class
  1354. *
  1355. * @return void
  1356. */
  1357. public function testHydrateBelongsToCustomEntity() {
  1358. $authorEntity = $this->getMockClass('\Cake\ORM\Entity', ['foo']);
  1359. $table = TableRegistry::get('articles');
  1360. TableRegistry::get('authors', [
  1361. 'entityClass' => '\\' . $authorEntity
  1362. ]);
  1363. $table->belongsTo('authors');
  1364. $query = new Query($this->connection, $table);
  1365. $results = $query->select()
  1366. ->contain('authors')
  1367. ->order(['articles.id' => 'asc'])
  1368. ->toArray();
  1369. $first = $results[0];
  1370. $this->assertInstanceOf($authorEntity, $first->author);
  1371. }
  1372. /**
  1373. * Test getting counts from queries.
  1374. *
  1375. * @return void
  1376. */
  1377. public function testCount() {
  1378. $table = TableRegistry::get('articles');
  1379. $result = $table->find('all')->count();
  1380. $this->assertEquals(3, $result);
  1381. $query = $table->find('all')
  1382. ->where(['id >' => 1]);
  1383. $result = $query->count();
  1384. $this->assertEquals(2, $result);
  1385. $result = $query->all();
  1386. $this->assertEquals(['count' => 2], $result->first());
  1387. }
  1388. /**
  1389. * Test that count() returns correct results with group by.
  1390. *
  1391. * @return void
  1392. */
  1393. public function testCountWithGroup() {
  1394. $table = TableRegistry::get('articles');
  1395. $query = $table->find('all')
  1396. ->group(['published']);
  1397. $result = $query->count();
  1398. $this->assertEquals(1, $result);
  1399. }
  1400. /**
  1401. * Test update method.
  1402. *
  1403. * @return void
  1404. */
  1405. public function testUpdate() {
  1406. $table = TableRegistry::get('articles');
  1407. $result = $table->query()
  1408. ->update()
  1409. ->set(['title' => 'First'])
  1410. ->execute();
  1411. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1412. $this->assertTrue($result->rowCount() > 0);
  1413. }
  1414. /**
  1415. * Test insert method.
  1416. *
  1417. * @return void
  1418. */
  1419. public function testInsert() {
  1420. $table = TableRegistry::get('articles');
  1421. $result = $table->query()
  1422. ->insert(['title'])
  1423. ->values(['title' => 'First'])
  1424. ->values(['title' => 'Second'])
  1425. ->execute();
  1426. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1427. $this->assertEquals(2, $result->rowCount());
  1428. }
  1429. /**
  1430. * Test delete method.
  1431. *
  1432. * @return void
  1433. */
  1434. public function testDelete() {
  1435. $table = TableRegistry::get('articles');
  1436. $result = $table->query()
  1437. ->delete()
  1438. ->where(['id >=' => 1])
  1439. ->execute();
  1440. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1441. $this->assertTrue($result->rowCount() > 0);
  1442. }
  1443. /**
  1444. * Provides a list of collection methods that can be proxied
  1445. * from the query
  1446. *
  1447. * @return array
  1448. */
  1449. public function collectionMethodsProvider() {
  1450. $identity = function($a) {
  1451. return $a;
  1452. };
  1453. return [
  1454. ['filter', $identity],
  1455. ['reject', $identity],
  1456. ['every', $identity],
  1457. ['some', $identity],
  1458. ['contains', $identity],
  1459. ['map', $identity],
  1460. ['reduce', $identity],
  1461. ['extract', $identity],
  1462. ['max', $identity],
  1463. ['min', $identity],
  1464. ['sortBy', $identity],
  1465. ['groupBy', $identity],
  1466. ['countBy', $identity],
  1467. ['shuffle', $identity],
  1468. ['sample', $identity],
  1469. ['take', 1],
  1470. ['append', new \ArrayIterator],
  1471. ['compile', 1],
  1472. ];
  1473. }
  1474. /**
  1475. * Tests that query can proxy collection methods
  1476. *
  1477. * @dataProvider collectionMethodsProvider
  1478. * @return void
  1479. */
  1480. public function testCollectionProxy($method, $arg) {
  1481. $query = $this->getMock(
  1482. '\Cake\ORM\Query', ['getResults'],
  1483. [$this->connection, $this->table]
  1484. );
  1485. $query->select();
  1486. $resultSet = $this->getMock('\Cake\ORM\ResultSet', [], [$query, null]);
  1487. $query->expects($this->once())
  1488. ->method('getResults')
  1489. ->will($this->returnValue($resultSet));
  1490. $resultSet->expects($this->once())
  1491. ->method($method)
  1492. ->with($arg, 'extra')
  1493. ->will($this->returnValue(new \Cake\Collection\Collection([])));
  1494. $this->assertInstanceOf(
  1495. '\Cake\Collection\Collection',
  1496. $query->{$method}($arg, 'extra')
  1497. );
  1498. }
  1499. /**
  1500. * Tests that calling an inexistent method in query throws an
  1501. * exception
  1502. *
  1503. * @expectedException \BadMethodCallException
  1504. * @expectedExceptionMessage Unknown method "derpFilter"
  1505. * @return void
  1506. */
  1507. public function testCollectionProxyBadMethod() {
  1508. TableRegistry::get('articles')->find('all')->derpFilter();
  1509. }
  1510. /**
  1511. * cache() should fail on non select queries.
  1512. *
  1513. * @expectedException RuntimeException
  1514. * @return void
  1515. */
  1516. public function testCacheErrorOnNonSelect() {
  1517. $table = TableRegistry::get('articles', ['table' => 'articles']);
  1518. $query = new Query($this->connection, $table);
  1519. $query->insert(['test']);
  1520. $query->cache('my_key');
  1521. }
  1522. /**
  1523. * Integration test for query caching.
  1524. *
  1525. * @return void
  1526. */
  1527. public function testCacheReadIntegration() {
  1528. $query = $this->getMock(
  1529. '\Cake\ORM\Query', ['execute'],
  1530. [$this->connection, $this->table]
  1531. );
  1532. $resultSet = $this->getMock('\Cake\ORM\ResultSet', [], [$query, null]);
  1533. $query->expects($this->never())
  1534. ->method('execute');
  1535. $cacher = $this->getMock('Cake\Cache\CacheEngine');
  1536. $cacher->expects($this->once())
  1537. ->method('read')
  1538. ->with('my_key')
  1539. ->will($this->returnValue($resultSet));
  1540. $query->cache('my_key', $cacher)
  1541. ->where(['id' => 1]);
  1542. $results = $query->all();
  1543. $this->assertSame($resultSet, $results);
  1544. }
  1545. /**
  1546. * Integration test for query caching.
  1547. *
  1548. * @return void
  1549. */
  1550. public function testCacheWriteIntegration() {
  1551. $table = TableRegistry::get('Articles');
  1552. $query = new Query($this->connection, $table);
  1553. $query->select(['id', 'title']);
  1554. $cacher = $this->getMock('Cake\Cache\CacheEngine');
  1555. $cacher->expects($this->once())
  1556. ->method('write')
  1557. ->with(
  1558. 'my_key',
  1559. $this->isInstanceOf('Cake\ORM\ResultSet')
  1560. );
  1561. $query->cache('my_key', $cacher)
  1562. ->where(['id' => 1]);
  1563. $query->all();
  1564. }
  1565. }