QueryRegressionTest.php 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\ORM;
  16. use Cake\Core\Plugin;
  17. use Cake\I18n\Time;
  18. use Cake\ORM\TableRegistry;
  19. use Cake\TestSuite\TestCase;
  20. /**
  21. * Contains regression test for the Query builder
  22. */
  23. class QueryRegressionTest extends TestCase
  24. {
  25. /**
  26. * Fixture to be used
  27. *
  28. * @var array
  29. */
  30. public $fixtures = [
  31. 'core.articles',
  32. 'core.tags',
  33. 'core.articles_tags',
  34. 'core.authors',
  35. 'core.authors_tags',
  36. 'core.comments',
  37. 'core.featured_tags',
  38. 'core.special_tags',
  39. 'core.tags_translations',
  40. 'core.translates',
  41. 'core.users'
  42. ];
  43. public $autoFixtures = false;
  44. /**
  45. * Tear down
  46. *
  47. * @return void
  48. */
  49. public function tearDown()
  50. {
  51. parent::tearDown();
  52. TableRegistry::clear();
  53. }
  54. /**
  55. * Test for https://github.com/cakephp/cakephp/issues/3087
  56. *
  57. * @return void
  58. */
  59. public function testSelectTimestampColumn()
  60. {
  61. $this->loadFixtures('Users');
  62. $table = TableRegistry::get('users');
  63. $user = $table->find()->where(['id' => 1])->first();
  64. $this->assertEquals(new Time('2007-03-17 01:16:23'), $user->created);
  65. $this->assertEquals(new Time('2007-03-17 01:18:31'), $user->updated);
  66. }
  67. /**
  68. * Tests that EagerLoader does not try to create queries for associations having no
  69. * keys to compare against
  70. *
  71. * @return void
  72. */
  73. public function testEagerLoadingFromEmptyResults()
  74. {
  75. $this->loadFixtures('Articles', 'Tags', 'ArticlesTags');
  76. $table = TableRegistry::get('Articles');
  77. $table->belongsToMany('ArticlesTags');
  78. $results = $table->find()->where(['id >' => 100])->contain('ArticlesTags')->toArray();
  79. $this->assertEmpty($results);
  80. }
  81. /**
  82. * Tests that eagerloading belongsToMany with find list fails with a helpful message.
  83. *
  84. * @expectedException \InvalidArgumentException
  85. * @return void
  86. */
  87. public function testEagerLoadingBelongsToManyList()
  88. {
  89. $this->loadFixtures('Articles', 'Tags', 'ArticlesTags');
  90. $table = TableRegistry::get('Articles');
  91. $table->belongsToMany('Tags', [
  92. 'finder' => 'list'
  93. ]);
  94. $table->find()->contain('Tags')->toArray();
  95. }
  96. /**
  97. * Tests that duplicate aliases in contain() can be used, even when they would
  98. * naturally be attached to the query instead of eagerly loaded. What should
  99. * happen here is that One of the duplicates will be changed to be loaded using
  100. * an extra query, but yielding the same results
  101. *
  102. * @return void
  103. */
  104. public function testDuplicateAttachableAliases()
  105. {
  106. $this->loadFixtures('Articles', 'Tags', 'ArticlesTags', 'Authors');
  107. TableRegistry::get('Stuff', ['table' => 'tags']);
  108. TableRegistry::get('Things', ['table' => 'articles_tags']);
  109. $table = TableRegistry::get('Articles');
  110. $table->belongsTo('Authors');
  111. $table->hasOne('Things', ['propertyName' => 'articles_tag']);
  112. $table->Authors->target()->hasOne('Stuff', [
  113. 'foreignKey' => 'id',
  114. 'propertyName' => 'favorite_tag'
  115. ]);
  116. $table->Things->target()->belongsTo('Stuff', [
  117. 'foreignKey' => 'tag_id',
  118. 'propertyName' => 'foo'
  119. ]);
  120. $results = $table->find()
  121. ->contain(['Authors.Stuff', 'Things.Stuff'])
  122. ->order(['Articles.id' => 'ASC'])
  123. ->toArray();
  124. $this->assertCount(5, $results);
  125. $this->assertEquals(1, $results[0]->articles_tag->foo->id);
  126. $this->assertEquals(1, $results[0]->author->favorite_tag->id);
  127. $this->assertEquals(2, $results[1]->articles_tag->foo->id);
  128. $this->assertEquals(1, $results[2]->articles_tag->foo->id);
  129. $this->assertEquals(3, $results[2]->author->favorite_tag->id);
  130. $this->assertEquals(3, $results[3]->articles_tag->foo->id);
  131. $this->assertEquals(3, $results[3]->author->favorite_tag->id);
  132. }
  133. /**
  134. * Test for https://github.com/cakephp/cakephp/issues/3410
  135. *
  136. * @return void
  137. */
  138. public function testNullableTimeColumn()
  139. {
  140. $this->loadFixtures('Users');
  141. $table = TableRegistry::get('users');
  142. $entity = $table->newEntity(['username' => 'derp', 'created' => null]);
  143. $this->assertSame($entity, $table->save($entity));
  144. $this->assertNull($entity->created);
  145. }
  146. /**
  147. * Test for https://github.com/cakephp/cakephp/issues/3626
  148. *
  149. * Checks that join data is actually created and not tried to be updated every time
  150. * @return void
  151. */
  152. public function testCreateJointData()
  153. {
  154. $this->loadFixtures('Articles', 'Tags', 'SpecialTags');
  155. $articles = TableRegistry::get('Articles');
  156. $articles->belongsToMany('Highlights', [
  157. 'className' => 'TestApp\Model\Table\TagsTable',
  158. 'foreignKey' => 'article_id',
  159. 'targetForeignKey' => 'tag_id',
  160. 'through' => 'SpecialTags'
  161. ]);
  162. $entity = $articles->get(2);
  163. $data = [
  164. 'id' => 2,
  165. 'highlights' => [
  166. [
  167. 'name' => 'New Special Tag',
  168. '_joinData' => ['highlighted' => true, 'highlighted_time' => '2014-06-01 10:10:00']
  169. ]
  170. ]
  171. ];
  172. $entity = $articles->patchEntity($entity, $data, ['Highlights._joinData']);
  173. $articles->save($entity);
  174. $entity = $articles->get(2, ['contain' => ['Highlights']]);
  175. $this->assertEquals(4, $entity->highlights[0]->_joinData->tag_id);
  176. $this->assertEquals('2014-06-01', $entity->highlights[0]->_joinData->highlighted_time->format('Y-m-d'));
  177. }
  178. /**
  179. * Tests that the junction table instance taken from both sides of a belongsToMany
  180. * relationship is actually the same object.
  181. *
  182. * @return void
  183. */
  184. public function testReciprocalBelongsToMany()
  185. {
  186. $this->loadFixtures('Articles', 'Tags', 'ArticlesTags');
  187. $articles = TableRegistry::get('Articles');
  188. $tags = TableRegistry::get('Tags');
  189. $articles->belongsToMany('Tags');
  190. $tags->belongsToMany('Articles');
  191. $left = $articles->Tags->junction();
  192. $right = $tags->Articles->junction();
  193. $this->assertSame($left, $right);
  194. }
  195. /**
  196. * Test for https://github.com/cakephp/cakephp/issues/4253
  197. *
  198. * Makes sure that the belongsToMany association is not overwritten with conflicting information
  199. * by any of the sides when the junction() function is invoked
  200. *
  201. * @return void
  202. */
  203. public function testReciprocalBelongsToManyNoOverwrite()
  204. {
  205. $this->loadFixtures('Articles', 'Tags', 'ArticlesTags');
  206. $articles = TableRegistry::get('Articles');
  207. $tags = TableRegistry::get('Tags');
  208. $articles->belongsToMany('Tags');
  209. $tags->belongsToMany('Articles');
  210. $sub = $articles->Tags->find()->select(['Tags.id'])->matching('Articles', function ($q) {
  211. return $q->where(['Articles.id' => 1]);
  212. });
  213. $query = $articles->Tags->find()->where(['Tags.id NOT IN' => $sub]);
  214. $this->assertEquals(1, $query->count());
  215. }
  216. /**
  217. * Returns an array with the saving strategies for a belongsTo association
  218. *
  219. * @return array
  220. */
  221. public function strategyProvider()
  222. {
  223. return [
  224. ['append'],
  225. ['replace'],
  226. ];
  227. }
  228. /**
  229. * Test for https://github.com/cakephp/cakephp/issues/3677 and
  230. * https://github.com/cakephp/cakephp/issues/3714
  231. *
  232. * Checks that only relevant associations are passed when saving _joinData
  233. * Tests that _joinData can also save deeper associations
  234. *
  235. * @dataProvider strategyProvider
  236. * @param string $strategy
  237. * @return void
  238. */
  239. public function testBelongsToManyDeepSave($strategy)
  240. {
  241. $this->loadFixtures('Articles', 'Tags', 'SpecialTags', 'Authors');
  242. $articles = TableRegistry::get('Articles');
  243. $articles->belongsToMany('Highlights', [
  244. 'className' => 'TestApp\Model\Table\TagsTable',
  245. 'foreignKey' => 'article_id',
  246. 'targetForeignKey' => 'tag_id',
  247. 'through' => 'SpecialTags',
  248. 'saveStrategy' => $strategy
  249. ]);
  250. $articles->Highlights->junction()->belongsTo('Authors');
  251. $articles->Highlights->hasOne('Authors', [
  252. 'foreignKey' => 'id'
  253. ]);
  254. $entity = $articles->get(2, ['contain' => ['Highlights']]);
  255. $data = [
  256. 'highlights' => [
  257. [
  258. 'name' => 'New Special Tag',
  259. '_joinData' => [
  260. 'highlighted' => true,
  261. 'highlighted_time' => '2014-06-01 10:10:00',
  262. 'author' => [
  263. 'name' => 'mariano'
  264. ]
  265. ],
  266. 'author' => ['name' => 'mark']
  267. ]
  268. ]
  269. ];
  270. $options = [
  271. 'associated' => [
  272. 'Highlights._joinData.Authors', 'Highlights.Authors'
  273. ]
  274. ];
  275. $entity = $articles->patchEntity($entity, $data, $options);
  276. $articles->save($entity, $options);
  277. $entity = $articles->get(2, [
  278. 'contain' => [
  279. 'SpecialTags' => ['sort' => ['SpecialTags.id' => 'ASC']],
  280. 'SpecialTags.Authors',
  281. 'Highlights.Authors'
  282. ]
  283. ]);
  284. $this->assertEquals('mark', end($entity->highlights)->author->name);
  285. $lastTag = end($entity->special_tags);
  286. $this->assertTrue($lastTag->highlighted);
  287. $this->assertEquals('2014-06-01 10:10:00', $lastTag->highlighted_time->format('Y-m-d H:i:s'));
  288. $this->assertEquals('mariano', $lastTag->author->name);
  289. }
  290. /**
  291. * Tests that no exceptions are generated becuase of ambiguous column names in queries
  292. * during a save operation
  293. *
  294. * @see https://github.com/cakephp/cakephp/issues/3803
  295. * @return void
  296. */
  297. public function testSaveWithCallbacks()
  298. {
  299. $this->loadFixtures('Articles', 'Authors');
  300. $articles = TableRegistry::get('Articles');
  301. $articles->belongsTo('Authors');
  302. $articles->eventManager()->attach(function ($event, $query) {
  303. return $query->contain('Authors');
  304. }, 'Model.beforeFind');
  305. $article = $articles->newEntity();
  306. $article->title = 'Foo';
  307. $article->body = 'Bar';
  308. $this->assertSame($article, $articles->save($article));
  309. }
  310. /**
  311. * Test that save() works with entities containing expressions
  312. * as properties.
  313. *
  314. * @return void
  315. */
  316. public function testSaveWithExpressionProperty()
  317. {
  318. $this->loadFixtures('Articles');
  319. $articles = TableRegistry::get('Articles');
  320. $article = $articles->newEntity();
  321. $article->title = new \Cake\Database\Expression\QueryExpression("SELECT 'jose'");
  322. $this->assertSame($article, $articles->save($article));
  323. }
  324. /**
  325. * Tests that whe saving deep associations for a belongsToMany property,
  326. * data is not removed becuase of excesive associations filtering.
  327. *
  328. * @see https://github.com/cakephp/cakephp/issues/4009
  329. * @return void
  330. */
  331. public function testBelongsToManyDeepSave2()
  332. {
  333. $this->loadFixtures('Articles', 'Tags', 'SpecialTags');
  334. $articles = TableRegistry::get('Articles');
  335. $articles->belongsToMany('Highlights', [
  336. 'className' => 'TestApp\Model\Table\TagsTable',
  337. 'foreignKey' => 'article_id',
  338. 'targetForeignKey' => 'tag_id',
  339. 'through' => 'SpecialTags',
  340. ]);
  341. $articles->Highlights->hasMany('TopArticles', [
  342. 'className' => 'TestApp\Model\Table\ArticlesTable',
  343. 'foreignKey' => 'author_id',
  344. ]);
  345. $entity = $articles->get(2, ['contain' => ['Highlights']]);
  346. $data = [
  347. 'highlights' => [
  348. [
  349. 'name' => 'New Special Tag',
  350. '_joinData' => [
  351. 'highlighted' => true,
  352. 'highlighted_time' => '2014-06-01 10:10:00',
  353. ],
  354. 'top_articles' => [
  355. ['title' => 'First top article'],
  356. ['title' => 'Second top article'],
  357. ]
  358. ]
  359. ]
  360. ];
  361. $options = [
  362. 'associated' => [
  363. 'Highlights._joinData', 'Highlights.TopArticles'
  364. ]
  365. ];
  366. $entity = $articles->patchEntity($entity, $data, $options);
  367. $articles->save($entity, $options);
  368. $entity = $articles->get(2, [
  369. 'contain' => [
  370. 'Highlights.TopArticles'
  371. ]
  372. ]);
  373. $highlights = $entity->highlights[0];
  374. $this->assertEquals('First top article', $highlights->top_articles[0]->title);
  375. $this->assertEquals('Second top article', $highlights->top_articles[1]->title);
  376. $this->assertEquals(
  377. new Time('2014-06-01 10:10:00'),
  378. $highlights->_joinData->highlighted_time
  379. );
  380. }
  381. /**
  382. * An integration test that spot checks that associations use the
  383. * correct alias names to generate queries.
  384. *
  385. * @return void
  386. */
  387. public function testPluginAssociationQueryGeneration()
  388. {
  389. $this->loadFixtures('Articles', 'Comments', 'Authors');
  390. Plugin::load('TestPlugin');
  391. $articles = TableRegistry::get('Articles');
  392. $articles->hasMany('TestPlugin.Comments');
  393. $articles->belongsTo('TestPlugin.Authors');
  394. $result = $articles->find()
  395. ->where(['Articles.id' => 2])
  396. ->contain(['Comments', 'Authors'])
  397. ->first();
  398. $this->assertNotEmpty(
  399. $result->comments[0]->id,
  400. 'No SQL error and comment exists.'
  401. );
  402. $this->assertNotEmpty(
  403. $result->author->id,
  404. 'No SQL error and author exists.'
  405. );
  406. }
  407. /**
  408. * Tests that loading associations having the same alias in the
  409. * joinable associations chain is not sensitive to the order in which
  410. * the associations are selected.
  411. *
  412. * @see https://github.com/cakephp/cakephp/issues/4454
  413. * @return void
  414. */
  415. public function testAssociationChainOrder()
  416. {
  417. $this->loadFixtures('Articles', 'Tags', 'ArticlesTags', 'Authors');
  418. $articles = TableRegistry::get('Articles');
  419. $articles->belongsTo('Authors');
  420. $articles->hasOne('ArticlesTags');
  421. $articlesTags = TableRegistry::get('ArticlesTags');
  422. $articlesTags->belongsTo('Authors', [
  423. 'foreignKey' => 'tag_id'
  424. ]);
  425. $resultA = $articles->find()
  426. ->contain(['ArticlesTags.Authors', 'Authors'])
  427. ->first();
  428. $resultB = $articles->find()
  429. ->contain(['Authors', 'ArticlesTags.Authors'])
  430. ->first();
  431. $this->assertEquals($resultA, $resultB);
  432. $this->assertNotEmpty($resultA->author);
  433. $this->assertNotEmpty($resultA->articles_tag->author);
  434. }
  435. /**
  436. * Test that offset/limit are elided from subquery loads.
  437. *
  438. * @return void
  439. */
  440. public function testAssociationSubQueryNoOffset()
  441. {
  442. $this->loadFixtures('Articles', 'Translates');
  443. $table = TableRegistry::get('Articles');
  444. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  445. $table->locale('eng');
  446. $query = $table->find('translations')
  447. ->order(['Articles.id' => 'ASC'])
  448. ->limit(10)
  449. ->offset(1);
  450. $result = $query->toArray();
  451. $this->assertCount(2, $result);
  452. }
  453. /**
  454. * Tests that using the subquery strategy in a deep association returns the right results
  455. *
  456. * @see https://github.com/cakephp/cakephp/issues/4484
  457. * @return void
  458. */
  459. public function testDeepBelongsToManySubqueryStrategy()
  460. {
  461. $this->loadFixtures('Authors', 'Tags', 'Articles', 'ArticlesTags');
  462. $table = TableRegistry::get('Authors');
  463. $table->hasMany('Articles');
  464. $table->Articles->belongsToMany('Tags', [
  465. 'strategy' => 'subquery'
  466. ]);
  467. $result = $table->find()->contain(['Articles.Tags'])->toArray();
  468. $this->skipIf(count($result) == 0, 'No results, this test sometimes acts up on PHP 5.6');
  469. $this->assertEquals(
  470. ['tag1', 'tag3'],
  471. collection($result[2]->articles[0]->tags)->extract('name')->toArray()
  472. );
  473. }
  474. /**
  475. * Tests that using the subquery strategy in a deep association returns the right results
  476. *
  477. * @see https://github.com/cakephp/cakephp/issues/5769
  478. * @return void
  479. */
  480. public function testDeepBelongsToManySubqueryStrategy2()
  481. {
  482. $this->loadFixtures('Articles', 'Authors', 'Tags', 'Authors', 'AuthorsTags');
  483. $table = TableRegistry::get('Authors');
  484. $table->hasMany('Articles');
  485. $table->Articles->belongsToMany('Tags', [
  486. 'strategy' => 'subquery'
  487. ]);
  488. $table->belongsToMany('Tags', [
  489. 'strategy' => 'subquery',
  490. ]);
  491. $table->Articles->belongsTo('Authors');
  492. $result = $table->Articles->find()
  493. ->where(['Authors.id >' => 1])
  494. ->contain(['Authors.Tags'])
  495. ->toArray();
  496. $this->assertEquals(
  497. ['tag1', 'tag2'],
  498. collection($result[0]->author->tags)->extract('name')->toArray()
  499. );
  500. $this->assertEquals(3, $result[0]->author->id);
  501. }
  502. /**
  503. * Tests that finding on a table with a primary key other than `id` will work
  504. * seamlessly with either select or subquery.
  505. *
  506. * @see https://github.com/cakephp/cakephp/issues/6781
  507. * @return void
  508. */
  509. public function testDeepHasManyEitherStrategy()
  510. {
  511. $this->loadFixtures('Tags', 'FeaturedTags', 'TagsTranslations');
  512. $tags = TableRegistry::get('Tags');
  513. $this->skipIf(
  514. $tags->connection()->driver() instanceof \Cake\Database\Driver\Sqlserver,
  515. 'SQL server is temporarily weird in this test, will investigate later'
  516. );
  517. $tags = TableRegistry::get('Tags');
  518. $featuredTags = TableRegistry::get('FeaturedTags');
  519. $featuredTags->belongsTo('Tags');
  520. $tags->hasMany('TagsTranslations', [
  521. 'foreignKey' => 'id',
  522. 'strategy' => 'select'
  523. ]);
  524. $findViaSelect = $featuredTags
  525. ->find()
  526. ->where(['FeaturedTags.tag_id' => 2])
  527. ->contain('Tags.TagsTranslations')
  528. ->all();
  529. $tags->hasMany('TagsTranslations', [
  530. 'foreignKey' => 'id',
  531. 'strategy' => 'subquery'
  532. ]);
  533. $findViaSubquery = $featuredTags
  534. ->find()
  535. ->where(['FeaturedTags.tag_id' => 2])
  536. ->contain('Tags.TagsTranslations')
  537. ->all();
  538. $expected = [2 => 'tag 2 translated into en_us'];
  539. $this->assertEquals($expected, $findViaSelect->combine('tag_id', 'tag.tags_translations.0.name')->toArray());
  540. $this->assertEquals($expected, $findViaSubquery->combine('tag_id', 'tag.tags_translations.0.name')->toArray());
  541. }
  542. /**
  543. * Tests that getting the count of a query having containments return
  544. * the correct results
  545. *
  546. * @see https://github.com/cakephp/cakephp/issues/4511
  547. * @return void
  548. */
  549. public function testCountWithContain()
  550. {
  551. $this->loadFixtures('Articles', 'Authors');
  552. $table = TableRegistry::get('Articles');
  553. $table->belongsTo('Authors', ['joinType' => 'inner']);
  554. $count = $table
  555. ->find()
  556. ->contain(['Authors' => function ($q) {
  557. return $q->where(['Authors.id' => 1]);
  558. }])
  559. ->count();
  560. $this->assertEquals(2, $count);
  561. }
  562. /**
  563. * Tests that getting the count of a query with bind is correct
  564. *
  565. * @see https://github.com/cakephp/cakephp/issues/8466
  566. * @return void
  567. */
  568. public function testCountWithBind()
  569. {
  570. $this->loadFixtures('Articles');
  571. $table = TableRegistry::get('Articles');
  572. $query = $table
  573. ->find()
  574. ->select(['title', 'id'])
  575. ->where("title LIKE :val")
  576. ->group(['id', 'title'])
  577. ->bind(':val', '%Second%');
  578. $count = $query->count();
  579. $this->assertEquals(1, $count);
  580. }
  581. /**
  582. * Tests that bind in subqueries works.
  583. *
  584. * @return void
  585. */
  586. public function testSubqueryBind()
  587. {
  588. $this->loadFixtures('Articles');
  589. $table = TableRegistry::get('Articles');
  590. $sub = $table->find()
  591. ->select(['id'])
  592. ->where("title LIKE :val")
  593. ->bind(':val', 'Second %');
  594. $query = $table
  595. ->find()
  596. ->select(['title'])
  597. ->where(["id NOT IN" => $sub]);
  598. $result = $query->toArray();
  599. $this->assertCount(2, $result);
  600. $this->assertEquals('First Article', $result[0]->title);
  601. $this->assertEquals('Third Article', $result[1]->title);
  602. }
  603. /**
  604. * Test that deep containments don't generate empty entities for
  605. * intermediary relations.
  606. *
  607. * @return void
  608. */
  609. public function testContainNoEmptyAssociatedObjects()
  610. {
  611. $this->loadFixtures('Comments', 'Users', 'Articles');
  612. $comments = TableRegistry::get('Comments');
  613. $comments->belongsTo('Users');
  614. $users = TableRegistry::get('Users');
  615. $users->hasMany('Articles', [
  616. 'foreignKey' => 'author_id'
  617. ]);
  618. $comments->updateAll(['user_id' => 99], ['id' => 1]);
  619. $result = $comments->find()
  620. ->contain(['Users'])
  621. ->where(['Comments.id' => 1])
  622. ->first();
  623. $this->assertNull($result->user, 'No record should be null.');
  624. $result = $comments->find()
  625. ->contain(['Users', 'Users.Articles'])
  626. ->where(['Comments.id' => 1])
  627. ->first();
  628. $this->assertNull($result->user, 'No record should be null.');
  629. }
  630. /**
  631. * Tests that using a comparison expression inside an OR condition works
  632. *
  633. * @see https://github.com/cakephp/cakephp/issues/5081
  634. * @return void
  635. */
  636. public function testOrConditionsWithExpression()
  637. {
  638. $this->loadFixtures('Articles');
  639. $table = TableRegistry::get('Articles');
  640. $query = $table->find();
  641. $query->where([
  642. 'OR' => [
  643. new \Cake\Database\Expression\Comparison('id', 1, 'integer', '>'),
  644. new \Cake\Database\Expression\Comparison('id', 3, 'integer', '<')
  645. ]
  646. ]);
  647. $results = $query->toArray();
  648. $this->assertCount(3, $results);
  649. }
  650. /**
  651. * Tests that calling count on a query having a union works correctly
  652. *
  653. * @see https://github.com/cakephp/cakephp/issues/5107
  654. * @return void
  655. */
  656. public function testCountWithUnionQuery()
  657. {
  658. $this->loadFixtures('Articles');
  659. $table = TableRegistry::get('Articles');
  660. $query = $table->find()->where(['id' => 1]);
  661. $query2 = $table->find()->where(['id' => 2]);
  662. $query->union($query2);
  663. $this->assertEquals(2, $query->count());
  664. }
  665. /**
  666. * Integration test when selecting no fields on the primary table.
  667. *
  668. * @return void
  669. */
  670. public function testSelectNoFieldsOnPrimaryAlias()
  671. {
  672. $this->loadFixtures('Articles', 'Users');
  673. $table = TableRegistry::get('Articles');
  674. $table->belongsTo('Users');
  675. $query = $table->find()
  676. ->select(['Users__id' => 'id']);
  677. $results = $query->toArray();
  678. $this->assertCount(3, $results);
  679. }
  680. /**
  681. * Tests that calling first on the query results will not remove all other results
  682. * from the set.
  683. *
  684. * @return void
  685. */
  686. public function testFirstOnResultSet()
  687. {
  688. $this->loadFixtures('Articles');
  689. $results = TableRegistry::get('Articles')->find()->all();
  690. $this->assertEquals(3, $results->count());
  691. $this->assertNotNull($results->first());
  692. $this->assertCount(3, $results->toArray());
  693. }
  694. /**
  695. * Checks that matching and contain can be called for the same belongsTo association
  696. *
  697. * @see https://github.com/cakephp/cakephp/issues/5463
  698. * @return void
  699. */
  700. public function testFindMatchingAndContain()
  701. {
  702. $this->loadFixtures('Articles', 'Authors');
  703. $table = TableRegistry::get('Articles');
  704. $table->belongsTo('Authors');
  705. $article = $table->find()
  706. ->contain('Authors')
  707. ->matching('Authors', function ($q) {
  708. return $q->where(['Authors.id' => 1]);
  709. })
  710. ->first();
  711. $this->assertNotNull($article->author);
  712. $this->assertEquals($article->author, $article->_matchingData['Authors']);
  713. }
  714. /**
  715. * Checks that matching and contain can be called for the same belongsTo association
  716. *
  717. * @see https://github.com/cakephp/cakephp/issues/5463
  718. * @return void
  719. */
  720. public function testFindMatchingAndContainWithSubquery()
  721. {
  722. $this->loadFixtures('Articles', 'Authors', 'Tags', 'ArticlesTags');
  723. $table = TableRegistry::get('authors');
  724. $table->hasMany('articles', ['strategy' => 'subquery']);
  725. $table->articles->belongsToMany('tags');
  726. $result = $table->find()
  727. ->matching('articles.tags', function ($q) {
  728. return $q->where(['tags.id' => 2]);
  729. })
  730. ->contain('articles');
  731. $this->assertCount(2, $result->first()->articles);
  732. }
  733. /**
  734. * Tests that matching does not overwrite associations in contain
  735. *
  736. * @see https://github.com/cakephp/cakephp/issues/5584
  737. * @return void
  738. */
  739. public function testFindMatchingOverwrite()
  740. {
  741. $this->loadFixtures('Articles', 'Comments', 'Tags', 'ArticlesTags');
  742. $comments = TableRegistry::get('Comments');
  743. $comments->belongsTo('Articles');
  744. $articles = TableRegistry::get('Articles');
  745. $articles->belongsToMany('Tags');
  746. $result = $comments
  747. ->find()
  748. ->matching('Articles.Tags', function ($q) {
  749. return $q->where(['Tags.id' => 2]);
  750. })
  751. ->contain('Articles')
  752. ->first();
  753. $this->assertEquals(1, $result->id);
  754. $this->assertEquals(1, $result->_matchingData['Articles']->id);
  755. $this->assertEquals(2, $result->_matchingData['Tags']->id);
  756. $this->assertNotNull($result->article);
  757. $this->assertEquals($result->article, $result->_matchingData['Articles']);
  758. }
  759. /**
  760. * Tests that matching does not overwrite associations in contain
  761. *
  762. * @see https://github.com/cakephp/cakephp/issues/5584
  763. * @return void
  764. */
  765. public function testFindMatchingOverwrite2()
  766. {
  767. $this->loadFixtures('Articles', 'Comments', 'Tags', 'ArticlesTags', 'Authors');
  768. $comments = TableRegistry::get('Comments');
  769. $comments->belongsTo('Articles');
  770. $articles = TableRegistry::get('Articles');
  771. $articles->belongsTo('Authors');
  772. $articles->belongsToMany('Tags');
  773. $result = $comments
  774. ->find()
  775. ->matching('Articles.Tags', function ($q) {
  776. return $q->where(['Tags.id' => 2]);
  777. })
  778. ->contain('Articles.Authors')
  779. ->first();
  780. $this->assertNotNull($result->article->author);
  781. }
  782. /**
  783. * Tests that trying to contain an inexistent association
  784. * throws an exception and not a fatal error.
  785. *
  786. * @expectedException InvalidArgumentException
  787. * @return void
  788. */
  789. public function testQueryNotFatalError()
  790. {
  791. $this->loadFixtures('Comments');
  792. $comments = TableRegistry::get('Comments');
  793. $comments->find()->contain('Deprs')->all();
  794. }
  795. /**
  796. * Tests that using matching and contain on belongsTo associations
  797. * works correctly.
  798. *
  799. * @see https://github.com/cakephp/cakephp/issues/5721
  800. * @return void
  801. */
  802. public function testFindMatchingWithContain()
  803. {
  804. $this->loadFixtures('Articles', 'Comments', 'Users');
  805. $comments = TableRegistry::get('Comments');
  806. $comments->belongsTo('Articles');
  807. $comments->belongsTo('Users');
  808. $result = $comments->find()
  809. ->contain(['Articles', 'Users'])
  810. ->matching('Articles', function ($q) {
  811. return $q->where(['Articles.id >=' => 1]);
  812. })
  813. ->matching('Users', function ($q) {
  814. return $q->where(['Users.id >=' => 1]);
  815. })
  816. ->order(['Comments.id' => 'ASC'])
  817. ->first();
  818. $this->assertInstanceOf('Cake\ORM\Entity', $result->article);
  819. $this->assertInstanceOf('Cake\ORM\Entity', $result->user);
  820. $this->assertEquals(2, $result->user->id);
  821. $this->assertEquals(1, $result->article->id);
  822. }
  823. /**
  824. * Tests that HasMany associations don't use duplicate PK values.
  825. *
  826. * @return void
  827. */
  828. public function testHasManyEagerLoadingUniqueKey()
  829. {
  830. $this->loadFixtures('Articles', 'Tags', 'ArticlesTags');
  831. $table = TableRegistry::get('ArticlesTags');
  832. $table->belongsTo('Articles', [
  833. 'strategy' => 'select'
  834. ]);
  835. $result = $table->find()
  836. ->contain(['Articles' => function ($q) {
  837. $result = $q->sql();
  838. $this->assertNotContains(':c2', $result, 'Only 2 bindings as there are only 2 rows.');
  839. $this->assertNotContains(':c3', $result, 'Only 2 bindings as there are only 2 rows.');
  840. return $q;
  841. }])
  842. ->toArray();
  843. $this->assertNotEmpty($result[0]->article);
  844. }
  845. /**
  846. * Tests that using contain but selecting no fields from the association
  847. * does not trigger any errors and fetches the right results.
  848. *
  849. * @see https://github.com/cakephp/cakephp/issues/6214
  850. * @return void
  851. */
  852. public function testContainWithNoFields()
  853. {
  854. $this->loadFixtures('Comments', 'Users');
  855. $table = TableRegistry::get('Comments');
  856. $table->belongsTo('Users');
  857. $results = $table->find()
  858. ->select(['Comments.id', 'Comments.user_id'])
  859. ->contain(['Users'])
  860. ->where(['Users.id' => 1])
  861. ->combine('id', 'user_id');
  862. $this->assertEquals([3 => 1, 4 => 1, 5 => 1], $results->toArray());
  863. }
  864. /**
  865. * Tests that find() and contained associations using computed fields doesn't error out.
  866. *
  867. * @see https://github.com/cakephp/cakephp/issues/9326
  868. * @return void
  869. */
  870. public function testContainWithComputedField()
  871. {
  872. $this->loadFixtures('Comments', 'Users');
  873. $table = TableRegistry::get('Users');
  874. $table->hasMany('Comments');
  875. $query = $table->find()->contain([
  876. 'Comments' => function ($q) {
  877. return $q->select([
  878. 'concat' => $q->func()->concat(['red', 'blue']),
  879. 'user_id'
  880. ]);
  881. }])
  882. ->where(['Users.id' => 2]);
  883. $results = $query->toArray();
  884. $this->assertCount(1, $results);
  885. $this->assertEquals('redblue', $results[0]->comments[0]->concat);
  886. }
  887. /**
  888. * Tests that using matching and selecting no fields for that association
  889. * will no trigger any errors and fetch the right results
  890. *
  891. * @see https://github.com/cakephp/cakephp/issues/6223
  892. * @return void
  893. */
  894. public function testMatchingWithNoFields()
  895. {
  896. $this->loadFixtures('Comments', 'Users');
  897. $table = TableRegistry::get('Users');
  898. $table->hasMany('Comments');
  899. $results = $table->find()
  900. ->select(['Users.id'])
  901. ->matching('Comments', function ($q) {
  902. return $q->where(['Comments.id' => 1]);
  903. })
  904. ->extract('id')
  905. ->toList();
  906. $this->assertEquals([2], $results);
  907. }
  908. /**
  909. * Test that empty conditions in a matching clause don't cause errors.
  910. *
  911. * @return void
  912. */
  913. public function testMatchingEmptyQuery()
  914. {
  915. $this->loadFixtures('Articles', 'Tags', 'ArticlesTags');
  916. $table = TableRegistry::get('Articles');
  917. $table->belongsToMany('Tags');
  918. $rows = $table->find()
  919. ->matching('Tags', function ($q) {
  920. return $q->where([]);
  921. })
  922. ->all();
  923. $this->assertNotEmpty($rows);
  924. $rows = $table->find()
  925. ->matching('Tags', function ($q) {
  926. return $q->where(null);
  927. })
  928. ->all();
  929. $this->assertNotEmpty($rows);
  930. }
  931. /**
  932. * Tests that using a subquery as part of an expression will not make invalid SQL
  933. *
  934. * @return void
  935. */
  936. public function testSubqueryInSelectExpression()
  937. {
  938. $this->loadFixtures('Comments');
  939. $table = TableRegistry::get('Comments');
  940. $ratio = $table->find()
  941. ->select(function ($query) use ($table) {
  942. $allCommentsCount = $table->find()->select($query->func()->count('*'));
  943. $countToFloat = $query->newExpr([$query->func()->count('*'), '1.0'])->type('*');
  944. return [
  945. 'ratio' => $query
  946. ->newExpr($countToFloat)
  947. ->add($allCommentsCount)
  948. ->type('/')
  949. ];
  950. })
  951. ->where(['user_id' => 1])
  952. ->first()
  953. ->ratio;
  954. $this->assertEquals(0.5, $ratio);
  955. }
  956. /**
  957. * Tests calling last on an empty table
  958. *
  959. * @see https://github.com/cakephp/cakephp/issues/6683
  960. * @return void
  961. */
  962. public function testFindLastOnEmptyTable()
  963. {
  964. $this->loadFixtures('Comments');
  965. $table = TableRegistry::get('Comments');
  966. $table->deleteAll(['1 = 1']);
  967. $this->assertEquals(0, $table->find()->count());
  968. $this->assertNull($table->find()->last());
  969. }
  970. /**
  971. * Tests calling contain in a nested closure
  972. *
  973. * @see https://github.com/cakephp/cakephp/issues/7591
  974. * @return void
  975. */
  976. public function testContainInNestedClosure()
  977. {
  978. $this->loadFixtures('Comments', 'Articles', 'Authors', 'Tags', 'AuthorsTags');
  979. $table = TableRegistry::get('Comments');
  980. $table->belongsTo('Articles');
  981. $table->Articles->belongsTo('Authors');
  982. $table->Articles->Authors->belongsToMany('Tags');
  983. $query = $table->find()->where(['Comments.id' => 5])->contain(['Articles' => function ($q) {
  984. return $q->contain(['Authors' => function ($q) {
  985. return $q->contain('Tags');
  986. }]);
  987. }]);
  988. $this->assertCount(2, $query->first()->article->author->tags);
  989. }
  990. /**
  991. * Test that the typemaps used in function expressions
  992. * create the correct results.
  993. *
  994. * @return void
  995. */
  996. public function testTypemapInFunctions()
  997. {
  998. $this->loadFixtures('Comments');
  999. $table = TableRegistry::get('Comments');
  1000. $table->updateAll(['published' => null], ['1 = 1']);
  1001. $query = $table->find();
  1002. $query->select([
  1003. 'id',
  1004. 'coalesced' => $query->func()->coalesce(
  1005. ['published' => 'identifier', -1],
  1006. ['integer']
  1007. )
  1008. ]);
  1009. $result = $query->all()->first();
  1010. $this->assertSame(
  1011. -1,
  1012. $result['coalesced'],
  1013. 'Output values for functions should be casted'
  1014. );
  1015. }
  1016. /**
  1017. * Test that the typemaps used in function expressions
  1018. * create the correct results.
  1019. *
  1020. * @return void
  1021. */
  1022. public function testTypemapInFunctions2()
  1023. {
  1024. $this->loadFixtures('Comments');
  1025. $table = TableRegistry::get('Comments');
  1026. $query = $table->find();
  1027. $query->select([
  1028. 'max' => $query->func()->max('created', ['datetime'])
  1029. ]);
  1030. $result = $query->all()->first();
  1031. $this->assertEquals(new Time('2007-03-18 10:55:23'), $result['max']);
  1032. }
  1033. /**
  1034. * Test that contain queries map types correctly.
  1035. *
  1036. * @return void
  1037. */
  1038. public function testBooleanConditionsInContain()
  1039. {
  1040. $this->loadFixtures('Articles', 'Tags', 'SpecialTags');
  1041. $table = TableRegistry::get('Articles');
  1042. $table->belongsToMany('Tags', [
  1043. 'foreignKey' => 'article_id',
  1044. 'associationForeignKey' => 'tag_id',
  1045. 'through' => 'SpecialTags'
  1046. ]);
  1047. $query = $table->find()
  1048. ->contain(['Tags' => function ($q) {
  1049. return $q->where(['SpecialTags.highlighted_time >' => new Time('2014-06-01 00:00:00')]);
  1050. }])
  1051. ->where(['Articles.id' => 2]);
  1052. $result = $query->first();
  1053. $this->assertEquals(2, $result->id);
  1054. $this->assertNotEmpty($result->tags, 'Missing tags');
  1055. $this->assertNotEmpty($result->tags[0]->_joinData, 'Missing join data');
  1056. }
  1057. /**
  1058. * Test that contain queries map types correctly.
  1059. *
  1060. * @return void
  1061. */
  1062. public function testComplexTypesInJoinedWhere()
  1063. {
  1064. $this->loadFixtures('Comments', 'Users');
  1065. $table = TableRegistry::get('Users');
  1066. $table->hasOne('Comments', [
  1067. 'foreignKey' => 'user_id',
  1068. ]);
  1069. $query = $table->find()
  1070. ->contain('Comments')
  1071. ->where([
  1072. 'Comments.updated >' => new \DateTime('2007-03-18 10:55:00')
  1073. ]);
  1074. $result = $query->first();
  1075. $this->assertNotEmpty($result);
  1076. $this->assertInstanceOf('Cake\I18n\Time', $result->comment->updated);
  1077. }
  1078. /**
  1079. * Test that nested contain queries map types correctly.
  1080. *
  1081. * @return void
  1082. */
  1083. public function testComplexNestedTypesInJoinedWhere()
  1084. {
  1085. $this->loadFixtures('Comments', 'Users', 'Articles');
  1086. $table = TableRegistry::get('Users');
  1087. $table->hasOne('Comments', [
  1088. 'foreignKey' => 'user_id',
  1089. ]);
  1090. $table->Comments->belongsTo('Articles');
  1091. $table->Comments->Articles->belongsTo('Authors', [
  1092. 'className' => 'Users',
  1093. 'foreignKey' => 'author_id'
  1094. ]);
  1095. $query = $table->find()
  1096. ->contain('Comments.Articles.Authors')
  1097. ->where([
  1098. 'Authors.created >' => new \DateTime('2007-03-17 01:16:00')
  1099. ]);
  1100. $result = $query->first();
  1101. $this->assertNotEmpty($result);
  1102. $this->assertInstanceOf('Cake\I18n\Time', $result->comment->article->author->updated);
  1103. }
  1104. /**
  1105. * Tests that it is possible to contain to fetch
  1106. * associations off of a junction table.
  1107. *
  1108. * @return void
  1109. */
  1110. public function testBelongsToManyJoinDataAssociation()
  1111. {
  1112. $this->loadFixtures('Authors', 'Articles', 'Tags', 'SpecialTags');
  1113. $articles = TableRegistry::get('Articles');
  1114. $tags = TableRegistry::get('Tags');
  1115. $tags->hasMany('SpecialTags');
  1116. $specialTags = TableRegistry::get('SpecialTags');
  1117. $specialTags->belongsTo('Authors');
  1118. $specialTags->belongsTo('Articles');
  1119. $specialTags->belongsTo('Tags');
  1120. $articles->belongsToMany('Tags', [
  1121. 'through' => $specialTags
  1122. ]);
  1123. $query = $articles->find()
  1124. ->contain(['Tags', 'Tags.SpecialTags.Authors'])
  1125. ->where(['Articles.id' => 1]);
  1126. $result = $query->first();
  1127. $this->assertNotEmpty($result->tags, 'Missing tags');
  1128. $this->assertNotEmpty($result->tags[0], 'Missing first tag');
  1129. $this->assertNotEmpty($result->tags[0]->_joinData, 'Missing _joinData');
  1130. $this->assertNotEmpty($result->tags[0]->special_tags[0]->author, 'Missing author on _joinData');
  1131. }
  1132. /**
  1133. * Tests that it is possible to use matching with dot notation
  1134. * even when part of the part of the path in the dot notation is
  1135. * shared for two different calls
  1136. *
  1137. * @return void
  1138. */
  1139. public function testDotNotationNotOverride()
  1140. {
  1141. $this->loadFixtures('Comments', 'Articles', 'Tags', 'Authors', 'SpecialTags');
  1142. $table = TableRegistry::get('Comments');
  1143. $articles = $table->belongsTo('Articles');
  1144. $specialTags = $articles->hasMany('SpecialTags');
  1145. $specialTags->belongsTo('Authors');
  1146. $specialTags->belongsTo('Tags');
  1147. $results = $table
  1148. ->find()
  1149. ->select(['name' => 'Authors.name', 'tag' => 'Tags.name'])
  1150. ->matching('Articles.SpecialTags.Tags')
  1151. ->matching('Articles.SpecialTags.Authors', function ($q) {
  1152. return $q->where(['Authors.id' => 2]);
  1153. })
  1154. ->distinct()
  1155. ->hydrate(false)
  1156. ->toArray();
  1157. $this->assertEquals([['name' => 'nate', 'tag' => 'tag1']], $results);
  1158. }
  1159. /**
  1160. * Test expression based ordering with unions.
  1161. *
  1162. * @return void
  1163. */
  1164. public function testComplexOrderWithUnion()
  1165. {
  1166. $this->loadFixtures('Comments');
  1167. $table = TableRegistry::get('Comments');
  1168. $query = $table->find();
  1169. $inner = $table->find()
  1170. ->select(['content' => 'comment'])
  1171. ->where(['id >' => 3]);
  1172. $inner2 = $table->find()
  1173. ->select(['content' => 'comment'])
  1174. ->where(['id <' => 3]);
  1175. $order = $query->func()->concat(['content' => 'literal', 'test']);
  1176. $query->select(['inside.content'])
  1177. ->from(['inside' => $inner->unionAll($inner2)])
  1178. ->orderAsc($order);
  1179. $results = $query->toArray();
  1180. $this->assertCount(5, $results);
  1181. }
  1182. /**
  1183. * Test that associations that are loaded with subqueries
  1184. * do not cause errors when the subquery has a limit & order clause.
  1185. *
  1186. * @return void
  1187. */
  1188. public function testEagerLoadOrderAndSubquery()
  1189. {
  1190. $this->loadFixtures('Articles', 'Comments');
  1191. $table = TableRegistry::get('Articles');
  1192. $table->hasMany('Comments', [
  1193. 'strategy' => 'subquery'
  1194. ]);
  1195. $query = $table->find()
  1196. ->select(['score' => 100])
  1197. ->autoFields(true)
  1198. ->contain(['Comments'])
  1199. ->limit(5)
  1200. ->order(['score' => 'desc']);
  1201. $result = $query->all();
  1202. $this->assertCount(3, $result);
  1203. }
  1204. /**
  1205. * Tests that decorating the results does not result in a memory leak
  1206. *
  1207. * @return void
  1208. */
  1209. public function testFormatResultsMemoryLeak()
  1210. {
  1211. $this->loadFixtures('Articles', 'Authors', 'Tags', 'ArticlesTags');
  1212. $this->skipIf(env('CODECOVERAGE') == 1, 'Running coverage this causes this tests to fail sometimes.');
  1213. $table = TableRegistry::get('Articles');
  1214. $table->belongsTo('Authors');
  1215. $table->belongsToMany('Tags');
  1216. gc_collect_cycles();
  1217. $memory = memory_get_usage() / 1024 / 1024;
  1218. foreach (range(1, 3) as $time) {
  1219. $table->find()
  1220. ->contain(['Authors', 'Tags'])
  1221. ->formatResults(function ($results) {
  1222. return $results;
  1223. })
  1224. ->all();
  1225. }
  1226. gc_collect_cycles();
  1227. $endMemory = memory_get_usage() / 1024 / 1024;
  1228. $this->assertWithinRange($endMemory, $memory, 1.25, 'Memory leak in ResultSet');
  1229. }
  1230. /**
  1231. * Tests that having bound placeholders in the order clause does not result
  1232. * in an error when trying to count a query.
  1233. *
  1234. * @return void
  1235. */
  1236. public function testCountWithComplexOrderBy()
  1237. {
  1238. $this->loadFixtures('Articles');
  1239. $table = TableRegistry::get('Articles');
  1240. $query = $table->find();
  1241. $query->orderDesc($query->newExpr()->addCase(
  1242. [$query->newExpr()->add(['id' => 3])],
  1243. [1, 0]
  1244. ));
  1245. $query->order(['title' => 'desc']);
  1246. // Executing the normal query before getting the count
  1247. $query->all();
  1248. $this->assertEquals(3, $query->count());
  1249. $table = TableRegistry::get('Articles');
  1250. $query = $table->find();
  1251. $query->orderDesc($query->newExpr()->addCase(
  1252. [$query->newExpr()->add(['id' => 3])],
  1253. [1, 0]
  1254. ));
  1255. $query->orderDesc($query->newExpr()->add(['id' => 3]));
  1256. // Not executing the query first, just getting the count
  1257. $this->assertEquals(3, $query->count());
  1258. }
  1259. /**
  1260. * Tests that the now() function expression can be used in the
  1261. * where clause of a query
  1262. *
  1263. * @see https://github.com/cakephp/cakephp/issues/7943
  1264. * @return void
  1265. */
  1266. public function testFunctionInWhereClause()
  1267. {
  1268. $this->loadFixtures('Comments');
  1269. $table = TableRegistry::get('Comments');
  1270. $table->updateAll(['updated' => Time::tomorrow()], ['id' => 6]);
  1271. $query = $table->find();
  1272. $result = $query->where(['updated >' => $query->func()->now('datetime')])->first();
  1273. $this->assertSame(6, $result->id);
  1274. }
  1275. }