QueryRegressionTest.php 58 KB

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