QueryRegressionTest.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101
  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\Query;
  19. use Cake\ORM\Table;
  20. use Cake\ORM\TableRegistry;
  21. use Cake\TestSuite\TestCase;
  22. /**
  23. * Contains regression test for the Query builder
  24. *
  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.articles_tags',
  36. 'core.authors',
  37. 'core.authors_tags',
  38. 'core.comments',
  39. 'core.featured_tags',
  40. 'core.special_tags',
  41. 'core.tags',
  42. 'core.tags_translations',
  43. 'core.translates',
  44. 'core.users'
  45. ];
  46. /**
  47. * Tear down
  48. *
  49. * @return void
  50. */
  51. public function tearDown()
  52. {
  53. parent::tearDown();
  54. TableRegistry::clear();
  55. }
  56. /**
  57. * Test for https://github.com/cakephp/cakephp/issues/3087
  58. *
  59. * @return void
  60. */
  61. public function testSelectTimestampColumn()
  62. {
  63. $table = TableRegistry::get('users');
  64. $user = $table->find()->where(['id' => 1])->first();
  65. $this->assertEquals(new Time('2007-03-17 01:16:23'), $user->created);
  66. $this->assertEquals(new Time('2007-03-17 01:18:31'), $user->updated);
  67. }
  68. /**
  69. * Tests that EagerLoader does not try to create queries for associations having no
  70. * keys to compare against
  71. *
  72. * @return void
  73. */
  74. public function testEagerLoadingFromEmptyResults()
  75. {
  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 \RuntimeException
  85. * @return void
  86. */
  87. public function testEagerLoadingBelongsToManyList()
  88. {
  89. $table = TableRegistry::get('Articles');
  90. $table->belongsToMany('Tags', [
  91. 'finder' => 'list'
  92. ]);
  93. $table->find()->contain('Tags')->toArray();
  94. }
  95. /**
  96. * Tests that duplicate aliases in contain() can be used, even when they would
  97. * naturally be attached to the query instead of eagerly loaded. What should
  98. * happen here is that One of the duplicates will be changed to be loaded using
  99. * an extra query, but yielding the same results
  100. *
  101. * @return void
  102. */
  103. public function testDuplicateAttachableAliases()
  104. {
  105. TableRegistry::get('Stuff', ['table' => 'tags']);
  106. TableRegistry::get('Things', ['table' => 'articles_tags']);
  107. $table = TableRegistry::get('Articles');
  108. $table->belongsTo('Authors');
  109. $table->hasOne('Things', ['propertyName' => 'articles_tag']);
  110. $table->Authors->target()->hasOne('Stuff', [
  111. 'foreignKey' => 'id',
  112. 'propertyName' => 'favorite_tag'
  113. ]);
  114. $table->Things->target()->belongsTo('Stuff', [
  115. 'foreignKey' => 'tag_id',
  116. 'propertyName' => 'foo'
  117. ]);
  118. $results = $table->find()
  119. ->contain(['Authors.Stuff', 'Things.Stuff'])
  120. ->order(['Articles.id' => 'ASC'])
  121. ->toArray();
  122. $this->assertEquals(1, $results[0]->articles_tag->foo->id);
  123. $this->assertEquals(1, $results[0]->author->favorite_tag->id);
  124. $this->assertEquals(2, $results[1]->articles_tag->foo->id);
  125. $this->assertEquals(1, $results[0]->author->favorite_tag->id);
  126. $this->assertEquals(1, $results[2]->articles_tag->foo->id);
  127. $this->assertEquals(3, $results[2]->author->favorite_tag->id);
  128. $this->assertEquals(3, $results[3]->articles_tag->foo->id);
  129. $this->assertEquals(3, $results[3]->author->favorite_tag->id);
  130. }
  131. /**
  132. * Test for https://github.com/cakephp/cakephp/issues/3410
  133. *
  134. * @return void
  135. */
  136. public function testNullableTimeColumn()
  137. {
  138. $table = TableRegistry::get('users');
  139. $entity = $table->newEntity(['username' => 'derp', 'created' => null]);
  140. $this->assertSame($entity, $table->save($entity));
  141. $this->assertNull($entity->created);
  142. }
  143. /**
  144. * Test for https://github.com/cakephp/cakephp/issues/3626
  145. *
  146. * Checks that join data is actually created and not tried to be updated every time
  147. * @return void
  148. */
  149. public function testCreateJointData()
  150. {
  151. $articles = TableRegistry::get('Articles');
  152. $articles->belongsToMany('Highlights', [
  153. 'className' => 'TestApp\Model\Table\TagsTable',
  154. 'foreignKey' => 'article_id',
  155. 'targetForeignKey' => 'tag_id',
  156. 'through' => 'SpecialTags'
  157. ]);
  158. $entity = $articles->get(2);
  159. $data = [
  160. 'id' => 2,
  161. 'highlights' => [
  162. [
  163. 'name' => 'New Special Tag',
  164. '_joinData' => ['highlighted' => true, 'highlighted_time' => '2014-06-01 10:10:00']
  165. ]
  166. ]
  167. ];
  168. $entity = $articles->patchEntity($entity, $data, ['Highlights._joinData']);
  169. $articles->save($entity);
  170. $entity = $articles->get(2, ['contain' => ['Highlights']]);
  171. $this->assertEquals(4, $entity->highlights[0]->_joinData->tag_id);
  172. $this->assertEquals('2014-06-01', $entity->highlights[0]->_joinData->highlighted_time->format('Y-m-d'));
  173. }
  174. /**
  175. * Tests that the junction table instance taken from both sides of a belongsToMany
  176. * relationship is actually the same object.
  177. *
  178. * @return void
  179. */
  180. public function testReciprocalBelongsToMany()
  181. {
  182. $articles = TableRegistry::get('Articles');
  183. $tags = TableRegistry::get('Tags');
  184. $articles->belongsToMany('Tags');
  185. $tags->belongsToMany('Articles');
  186. $left = $articles->Tags->junction();
  187. $right = $tags->Articles->junction();
  188. $this->assertSame($left, $right);
  189. }
  190. /**
  191. * Test for https://github.com/cakephp/cakephp/issues/4253
  192. *
  193. * Makes sure that the belongsToMany association is not overwritten with conflicting information
  194. * by any of the sides when the junction() function is invoked
  195. *
  196. * @return void
  197. */
  198. public function testReciprocalBelongsToMany2()
  199. {
  200. $articles = TableRegistry::get('Articles');
  201. $tags = TableRegistry::get('Tags');
  202. $articles->belongsToMany('Tags');
  203. $tags->belongsToMany('Articles');
  204. $sub = $articles->Tags->find()->select(['id'])->matching('Articles', function ($q) {
  205. return $q->where(['Articles.id' => 1]);
  206. });
  207. $query = $articles->Tags->find()->where(['id NOT IN' => $sub]);
  208. $this->assertEquals(1, $query->count());
  209. }
  210. /**
  211. * Returns an array with the saving strategies for a belongsTo association
  212. *
  213. * @return array
  214. */
  215. public function strategyProvider()
  216. {
  217. return [['append', 'replace']];
  218. }
  219. /**
  220. * Test for https://github.com/cakephp/cakephp/issues/3677 and
  221. * https://github.com/cakephp/cakephp/issues/3714
  222. *
  223. * Checks that only relevant associations are passed when saving _joinData
  224. * Tests that _joinData can also save deeper associations
  225. *
  226. * @dataProvider strategyProvider
  227. * @param string $strategy
  228. * @return void
  229. */
  230. public function testBelongsToManyDeepSave($strategy)
  231. {
  232. $articles = TableRegistry::get('Articles');
  233. $articles->belongsToMany('Highlights', [
  234. 'className' => 'TestApp\Model\Table\TagsTable',
  235. 'foreignKey' => 'article_id',
  236. 'targetForeignKey' => 'tag_id',
  237. 'through' => 'SpecialTags',
  238. 'saveStrategy' => $strategy
  239. ]);
  240. $articles->Highlights->junction()->belongsTo('Authors');
  241. $articles->Highlights->hasOne('Authors', [
  242. 'foreignKey' => 'id'
  243. ]);
  244. $entity = $articles->get(2, ['contain' => ['Highlights']]);
  245. $data = [
  246. 'highlights' => [
  247. [
  248. 'name' => 'New Special Tag',
  249. '_joinData' => [
  250. 'highlighted' => true,
  251. 'highlighted_time' => '2014-06-01 10:10:00',
  252. 'author' => [
  253. 'name' => 'mariano'
  254. ]
  255. ],
  256. 'author' => ['name' => 'mark']
  257. ]
  258. ]
  259. ];
  260. $options = [
  261. 'associated' => [
  262. 'Highlights._joinData.Authors', 'Highlights.Authors'
  263. ]
  264. ];
  265. $entity = $articles->patchEntity($entity, $data, $options);
  266. $articles->save($entity, $options);
  267. $entity = $articles->get(2, [
  268. 'contain' => [
  269. 'SpecialTags' => ['sort' => ['SpecialTags.id' => 'ASC']],
  270. 'SpecialTags.Authors',
  271. 'Highlights.Authors'
  272. ]
  273. ]);
  274. $this->assertEquals('mark', end($entity->highlights)->author->name);
  275. $lastTag = end($entity->special_tags);
  276. $this->assertTrue($lastTag->highlighted);
  277. $this->assertEquals('2014-06-01 10:10:00', $lastTag->highlighted_time->format('Y-m-d H:i:s'));
  278. $this->assertEquals('mariano', $lastTag->author->name);
  279. }
  280. /**
  281. * Tests that no exceptions are generated becuase of ambiguous column names in queries
  282. * during a save operation
  283. *
  284. * @see https://github.com/cakephp/cakephp/issues/3803
  285. * @return void
  286. */
  287. public function testSaveWithCallbacks()
  288. {
  289. $articles = TableRegistry::get('Articles');
  290. $articles->belongsTo('Authors');
  291. $articles->eventManager()->attach(function ($event, $query) {
  292. return $query->contain('Authors');
  293. }, 'Model.beforeFind');
  294. $article = $articles->newEntity();
  295. $article->title = 'Foo';
  296. $article->body = 'Bar';
  297. $this->assertSame($article, $articles->save($article));
  298. }
  299. /**
  300. * Test that save() works with entities containing expressions
  301. * as properties.
  302. *
  303. * @return void
  304. */
  305. public function testSaveWithExpressionProperty()
  306. {
  307. $articles = TableRegistry::get('Articles');
  308. $article = $articles->newEntity();
  309. $article->title = new \Cake\Database\Expression\QueryExpression("SELECT 'jose'");
  310. $this->assertSame($article, $articles->save($article));
  311. }
  312. /**
  313. * Tests that whe saving deep associations for a belongsToMany property,
  314. * data is not removed becuase of excesive associations filtering.
  315. *
  316. * @see https://github.com/cakephp/cakephp/issues/4009
  317. * @return void
  318. */
  319. public function testBelongsToManyDeepSave2()
  320. {
  321. $articles = TableRegistry::get('Articles');
  322. $articles->belongsToMany('Highlights', [
  323. 'className' => 'TestApp\Model\Table\TagsTable',
  324. 'foreignKey' => 'article_id',
  325. 'targetForeignKey' => 'tag_id',
  326. 'through' => 'SpecialTags',
  327. ]);
  328. $articles->Highlights->hasMany('TopArticles', [
  329. 'className' => 'TestApp\Model\Table\ArticlesTable',
  330. 'foreignKey' => 'author_id',
  331. ]);
  332. $entity = $articles->get(2, ['contain' => ['Highlights']]);
  333. $data = [
  334. 'highlights' => [
  335. [
  336. 'name' => 'New Special Tag',
  337. '_joinData' => [
  338. 'highlighted' => true,
  339. 'highlighted_time' => '2014-06-01 10:10:00',
  340. ],
  341. 'top_articles' => [
  342. ['title' => 'First top article'],
  343. ['title' => 'Second top article'],
  344. ]
  345. ]
  346. ]
  347. ];
  348. $options = [
  349. 'associated' => [
  350. 'Highlights._joinData', 'Highlights.TopArticles'
  351. ]
  352. ];
  353. $entity = $articles->patchEntity($entity, $data, $options);
  354. $articles->save($entity, $options);
  355. $entity = $articles->get(2, [
  356. 'contain' => [
  357. 'Highlights.TopArticles'
  358. ]
  359. ]);
  360. $highlights = $entity->highlights[0];
  361. $this->assertEquals('First top article', $highlights->top_articles[0]->title);
  362. $this->assertEquals('Second top article', $highlights->top_articles[1]->title);
  363. $this->assertEquals(
  364. new Time('2014-06-01 10:10:00'),
  365. $highlights->_joinData->highlighted_time
  366. );
  367. }
  368. /**
  369. * An integration test that spot checks that associations use the
  370. * correct alias names to generate queries.
  371. *
  372. * @return void
  373. */
  374. public function testPluginAssociationQueryGeneration()
  375. {
  376. Plugin::load('TestPlugin');
  377. $articles = TableRegistry::get('Articles');
  378. $articles->hasMany('TestPlugin.Comments');
  379. $articles->belongsTo('TestPlugin.Authors');
  380. $result = $articles->find()
  381. ->where(['Articles.id' => 2])
  382. ->contain(['Comments', 'Authors'])
  383. ->first();
  384. $this->assertNotEmpty(
  385. $result->comments[0]->id,
  386. 'No SQL error and comment exists.'
  387. );
  388. $this->assertNotEmpty(
  389. $result->author->id,
  390. 'No SQL error and author exists.'
  391. );
  392. }
  393. /**
  394. * Tests that loading associations having the same alias in the
  395. * joinable associations chain is not sensitive to the order in which
  396. * the associations are selected.
  397. *
  398. * @see https://github.com/cakephp/cakephp/issues/4454
  399. * @return void
  400. */
  401. public function testAssociationChainOrder()
  402. {
  403. $articles = TableRegistry::get('Articles');
  404. $articles->belongsTo('Authors');
  405. $articles->hasOne('ArticlesTags');
  406. $articlesTags = TableRegistry::get('ArticlesTags');
  407. $articlesTags->belongsTo('Authors', [
  408. 'foreignKey' => 'tag_id'
  409. ]);
  410. $resultA = $articles->find()
  411. ->contain(['ArticlesTags.Authors', 'Authors'])
  412. ->first();
  413. $resultB = $articles->find()
  414. ->contain(['Authors', 'ArticlesTags.Authors'])
  415. ->first();
  416. $this->assertEquals($resultA, $resultB);
  417. $this->assertNotEmpty($resultA->author);
  418. $this->assertNotEmpty($resultA->articles_tag->author);
  419. }
  420. /**
  421. * Test that offset/limit are elided from subquery loads.
  422. *
  423. * @return void
  424. */
  425. public function testAssociationSubQueryNoOffset()
  426. {
  427. $table = TableRegistry::get('Articles');
  428. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  429. $table->locale('eng');
  430. $query = $table->find('translations')
  431. ->order(['Articles.id' => 'ASC'])
  432. ->limit(10)
  433. ->offset(1);
  434. $result = $query->toArray();
  435. $this->assertCount(2, $result);
  436. }
  437. /**
  438. * Tests that using the subquery strategy in a deep association returns the right results
  439. *
  440. * @see https://github.com/cakephp/cakephp/issues/4484
  441. * @return void
  442. */
  443. public function testDeepBelongsToManySubqueryStrategy()
  444. {
  445. $table = TableRegistry::get('Authors');
  446. $table->hasMany('Articles');
  447. $table->Articles->belongsToMany('Tags', [
  448. 'strategy' => 'subquery'
  449. ]);
  450. $result = $table->find()->contain(['Articles.Tags'])->toArray();
  451. $this->assertEquals(
  452. ['tag1', 'tag3'],
  453. collection($result[2]->articles[0]->tags)->extract('name')->toArray()
  454. );
  455. }
  456. /**
  457. * Tests that using the subquery strategy in a deep association returns the right results
  458. *
  459. * @see https://github.com/cakephp/cakephp/issues/5769
  460. * @return void
  461. */
  462. public function testDeepBelongsToManySubqueryStrategy2()
  463. {
  464. $table = TableRegistry::get('Authors');
  465. $table->hasMany('Articles');
  466. $table->Articles->belongsToMany('Tags', [
  467. 'strategy' => 'subquery'
  468. ]);
  469. $table->belongsToMany('Tags', [
  470. 'strategy' => 'subquery',
  471. ]);
  472. $table->Articles->belongsTo('Authors');
  473. $result = $table->Articles->find()
  474. ->where(['Authors.id >' => 1])
  475. ->contain(['Authors.Tags'])
  476. ->toArray();
  477. $this->assertEquals(
  478. ['tag1', 'tag2'],
  479. collection($result[0]->author->tags)->extract('name')->toArray()
  480. );
  481. $this->assertEquals(3, $result[0]->author->id);
  482. }
  483. /**
  484. * Tests that finding on a table with a primary key other than `id` will work
  485. * seamlessly with either select or subquery.
  486. *
  487. * @see https://github.com/cakephp/cakephp/issues/6781
  488. * @return void
  489. */
  490. public function testDeepHasManyEitherStrategy()
  491. {
  492. $tags = TableRegistry::get('Tags');
  493. $featuredTags = TableRegistry::get('FeaturedTags');
  494. $featuredTags->belongsTo('Tags');
  495. $tags->hasMany('TagsTranslations', [
  496. 'foreignKey' => 'id',
  497. 'strategy' => 'select'
  498. ]);
  499. $findViaSelect = $featuredTags
  500. ->find()
  501. ->where(['FeaturedTags.tag_id' => 2])
  502. ->contain('Tags.TagsTranslations');
  503. $tags->hasMany('TagsTranslations', [
  504. 'foreignKey' => 'id',
  505. 'strategy' => 'subquery'
  506. ]);
  507. $findViaSubquery = $featuredTags
  508. ->find()
  509. ->where(['FeaturedTags.tag_id' => 2])
  510. ->contain('Tags.TagsTranslations');
  511. $expected = [2 => 'tag 2 translated into en_us'];
  512. $this->assertEquals($expected, $findViaSelect->combine('tag_id', 'tag.tags_translations.0.name')->toArray());
  513. $this->assertEquals($expected, $findViaSubquery->combine('tag_id', 'tag.tags_translations.0.name')->toArray());
  514. }
  515. /**
  516. * Tests that getting the count of a query having containments return
  517. * the correct results
  518. *
  519. * @see https://github.com/cakephp/cakephp/issues/4511
  520. * @return void
  521. */
  522. public function testCountWithContain()
  523. {
  524. $table = TableRegistry::get('Articles');
  525. $table->belongsTo('Authors', ['joinType' => 'inner']);
  526. $count = $table
  527. ->find()
  528. ->contain(['Authors' => function ($q) {
  529. return $q->where(['Authors.id' => 1]);
  530. }])
  531. ->count();
  532. $this->assertEquals(2, $count);
  533. }
  534. /**
  535. * Test that deep containments don't generate empty entities for
  536. * intermediary relations.
  537. *
  538. * @return void
  539. */
  540. public function testContainNoEmptyAssociatedObjects()
  541. {
  542. $comments = TableRegistry::get('Comments');
  543. $comments->belongsTo('Users');
  544. $users = TableRegistry::get('Users');
  545. $users->hasMany('Articles', [
  546. 'foreignKey' => 'author_id'
  547. ]);
  548. $comments->updateAll(['user_id' => 99], ['id' => 1]);
  549. $result = $comments->find()
  550. ->contain(['Users'])
  551. ->where(['Comments.id' => 1])
  552. ->first();
  553. $this->assertNull($result->user, 'No record should be null.');
  554. $result = $comments->find()
  555. ->contain(['Users', 'Users.Articles'])
  556. ->where(['Comments.id' => 1])
  557. ->first();
  558. $this->assertNull($result->user, 'No record should be null.');
  559. }
  560. /**
  561. * Tests that using a comparison expression inside an OR condition works
  562. *
  563. * @see https://github.com/cakephp/cakephp/issues/5081
  564. * @return void
  565. */
  566. public function testOrConditionsWithExpression()
  567. {
  568. $table = TableRegistry::get('Articles');
  569. $query = $table->find();
  570. $query->where([
  571. 'OR' => [
  572. new \Cake\Database\Expression\Comparison('id', 1, 'integer', '>'),
  573. new \Cake\Database\Expression\Comparison('id', 3, 'integer', '<')
  574. ]
  575. ]);
  576. $results = $query->toArray();
  577. $this->assertCount(3, $results);
  578. }
  579. /**
  580. * Tests that calling count on a query having a union works correctly
  581. *
  582. * @see https://github.com/cakephp/cakephp/issues/5107
  583. * @return void
  584. */
  585. public function testCountWithUnionQuery()
  586. {
  587. $table = TableRegistry::get('Articles');
  588. $query = $table->find()->where(['id' => 1]);
  589. $query2 = $table->find()->where(['id' => 2]);
  590. $query->union($query2);
  591. $this->assertEquals(2, $query->count());
  592. }
  593. /**
  594. * Integration test when selecting no fields on the primary table.
  595. *
  596. * @return void
  597. */
  598. public function testSelectNoFieldsOnPrimaryAlias()
  599. {
  600. $table = TableRegistry::get('Articles');
  601. $table->belongsTo('Users');
  602. $query = $table->find()
  603. ->select(['Users__id' => 'id']);
  604. $results = $query->toArray();
  605. $this->assertCount(3, $results);
  606. }
  607. /**
  608. * Tests that calling first on the query results will not remove all other results
  609. * from the set.
  610. *
  611. * @return void
  612. */
  613. public function testFirstOnResultSet()
  614. {
  615. $results = TableRegistry::get('Articles')->find()->all();
  616. $this->assertEquals(3, $results->count());
  617. $this->assertNotNull($results->first());
  618. $this->assertCount(3, $results->toArray());
  619. }
  620. /**
  621. * Checks that matching and contain can be called for the same belongsTo association
  622. *
  623. * @see https://github.com/cakephp/cakephp/issues/5463
  624. * @return void
  625. */
  626. public function testFindMatchingAndContain()
  627. {
  628. $table = TableRegistry::get('Articles');
  629. $table->belongsTo('Authors');
  630. $article = $table->find()
  631. ->contain('Authors')
  632. ->matching('Authors', function ($q) {
  633. return $q->where(['Authors.id' => 1]);
  634. })
  635. ->first();
  636. $this->assertNotNull($article->author);
  637. $this->assertEquals($article->author, $article->_matchingData['Authors']);
  638. }
  639. /**
  640. * Checks that matching and contain can be called for the same belongsTo association
  641. *
  642. * @see https://github.com/cakephp/cakephp/issues/5463
  643. * @return void
  644. */
  645. public function testFindMatchingAndContainWithSubquery()
  646. {
  647. $table = TableRegistry::get('authors');
  648. $table->hasMany('articles', ['strategy' => 'subquery']);
  649. $table->articles->belongsToMany('tags');
  650. $result = $table->find()
  651. ->matching('articles.tags', function ($q) {
  652. return $q->where(['tags.id' => 2]);
  653. })
  654. ->contain('articles');
  655. $this->assertCount(2, $result->first()->articles);
  656. }
  657. /**
  658. * Tests that matching does not overwrite associations in contain
  659. *
  660. * @see https://github.com/cakephp/cakephp/issues/5584
  661. * @return void
  662. */
  663. public function testFindMatchingOverwrite()
  664. {
  665. $comments = TableRegistry::get('Comments');
  666. $comments->belongsTo('Articles');
  667. $articles = TableRegistry::get('Articles');
  668. $articles->belongsToMany('Tags');
  669. $result = $comments
  670. ->find()
  671. ->matching('Articles.Tags', function ($q) {
  672. return $q->where(['Tags.id' => 2]);
  673. })
  674. ->contain('Articles')
  675. ->first();
  676. $this->assertEquals(1, $result->id);
  677. $this->assertEquals(1, $result->_matchingData['Articles']->id);
  678. $this->assertEquals(2, $result->_matchingData['Tags']->id);
  679. $this->assertNotNull($result->article);
  680. $this->assertEquals($result->article, $result->_matchingData['Articles']);
  681. }
  682. /**
  683. * Tests that matching does not overwrite associations in contain
  684. *
  685. * @see https://github.com/cakephp/cakephp/issues/5584
  686. * @return void
  687. */
  688. public function testFindMatchingOverwrite2()
  689. {
  690. $comments = TableRegistry::get('Comments');
  691. $comments->belongsTo('Articles');
  692. $articles = TableRegistry::get('Articles');
  693. $articles->belongsTo('Authors');
  694. $articles->belongsToMany('Tags');
  695. $result = $comments
  696. ->find()
  697. ->matching('Articles.Tags', function ($q) {
  698. return $q->where(['Tags.id' => 2]);
  699. })
  700. ->contain('Articles.Authors')
  701. ->first();
  702. $this->assertNotNull($result->article->author);
  703. }
  704. /**
  705. * Tests that trying to contain an inexistent association
  706. * throws an exception and not a fatal error.
  707. *
  708. * @expectedException InvalidArgumentException
  709. * @return void
  710. */
  711. public function testQueryNotFatalError()
  712. {
  713. $comments = TableRegistry::get('Comments');
  714. $comments->find()->contain('Deprs')->all();
  715. }
  716. /**
  717. * Tests that using matching and contain on belongsTo associations
  718. * works correctly.
  719. *
  720. * @see https://github.com/cakephp/cakephp/issues/5721
  721. * @return void
  722. */
  723. public function testFindMatchingWithContain()
  724. {
  725. $comments = TableRegistry::get('Comments');
  726. $comments->belongsTo('Articles');
  727. $comments->belongsTo('Users');
  728. $result = $comments->find()
  729. ->contain(['Articles', 'Users'])
  730. ->matching('Articles', function ($q) {
  731. return $q->where(['Articles.id >=' => 1]);
  732. })
  733. ->matching('Users', function ($q) {
  734. return $q->where(['Users.id >=' => 1]);
  735. })
  736. ->order(['Comments.id' => 'ASC'])
  737. ->first();
  738. $this->assertInstanceOf('Cake\ORM\Entity', $result->article);
  739. $this->assertInstanceOf('Cake\ORM\Entity', $result->user);
  740. $this->assertEquals(2, $result->user->id);
  741. $this->assertEquals(1, $result->article->id);
  742. }
  743. /**
  744. * Tests that HasMany associations don't use duplicate PK values.
  745. *
  746. * @return void
  747. */
  748. public function testHasManyEagerLoadingUniqueKey()
  749. {
  750. $table = TableRegistry::get('ArticlesTags');
  751. $table->belongsTo('Articles', [
  752. 'strategy' => 'select'
  753. ]);
  754. $result = $table->find()
  755. ->contain(['Articles' => function ($q) {
  756. $result = $q->sql();
  757. $this->assertNotContains(':c2', $result, 'Only 2 bindings as there are only 2 rows.');
  758. $this->assertNotContains(':c3', $result, 'Only 2 bindings as there are only 2 rows.');
  759. return $q;
  760. }])
  761. ->toArray();
  762. $this->assertNotEmpty($result[0]->article);
  763. }
  764. /**
  765. * Tests that using contain but selecting no fields from the association
  766. * does not trigger any errors and fetches the right results.
  767. *
  768. * @see https://github.com/cakephp/cakephp/issues/6214
  769. * @return void
  770. */
  771. public function testContainWithNoFields()
  772. {
  773. $table = TableRegistry::get('Comments');
  774. $table->belongsTo('Users');
  775. $results = $table->find()
  776. ->select(['Comments.id', 'Comments.user_id'])
  777. ->contain(['Users'])
  778. ->where(['Users.id' => 1])
  779. ->combine('id', 'user_id');
  780. $this->assertEquals([3 => 1, 4 => 1, 5 => 1], $results->toArray());
  781. }
  782. /**
  783. * Tests that using matching and selecting no fields for that association
  784. * will no trigger any errors and fetch the right results
  785. *
  786. * @see https://github.com/cakephp/cakephp/issues/6223
  787. * @return void
  788. */
  789. public function testMatchingWithNoFields()
  790. {
  791. $table = TableRegistry::get('Users');
  792. $table->hasMany('Comments');
  793. $results = $table->find()
  794. ->select(['Users.id'])
  795. ->matching('Comments', function ($q) {
  796. return $q->where(['Comments.id' => 1]);
  797. })
  798. ->extract('id')
  799. ->toList();
  800. $this->assertEquals([2], $results);
  801. }
  802. /**
  803. * Test that empty conditions in a matching clause don't cause errors.
  804. *
  805. * @return void
  806. */
  807. public function testMatchingEmptyQuery()
  808. {
  809. $table = TableRegistry::get('Articles');
  810. $table->belongsToMany('Tags');
  811. $rows = $table->find()
  812. ->matching('Tags', function ($q) {
  813. return $q->where([]);
  814. })
  815. ->all();
  816. $this->assertNotEmpty($rows);
  817. $rows = $table->find()
  818. ->matching('Tags', function ($q) {
  819. return $q->where(null);
  820. })
  821. ->all();
  822. $this->assertNotEmpty($rows);
  823. }
  824. /**
  825. * Tests that using a subquery as part of an expression will not make invalid SQL
  826. *
  827. * @return void
  828. */
  829. public function testSubqueryInSelectExpression()
  830. {
  831. $table = TableRegistry::get('Comments');
  832. $ratio = $table->find()
  833. ->select(function ($query) use ($table) {
  834. $allCommentsCount = $table->find()->select($query->func()->count('*'));
  835. $countToFloat = $query->newExpr([$query->func()->count('*'), '1.0'])->type('*');
  836. return [
  837. 'ratio' => $query
  838. ->newExpr($countToFloat)
  839. ->add($allCommentsCount)
  840. ->type('/')
  841. ];
  842. })
  843. ->where(['user_id' => 1])
  844. ->first()
  845. ->ratio;
  846. $this->assertEquals(0.5, $ratio);
  847. }
  848. /**
  849. * Tests calling last on an empty table
  850. *
  851. * @see https://github.com/cakephp/cakephp/issues/6683
  852. * @return void
  853. */
  854. public function testFindLastOnEmptyTable()
  855. {
  856. $table = TableRegistry::get('Comments');
  857. $table->deleteAll(['1 = 1']);
  858. $this->assertEquals(0, $table->find()->count());
  859. $this->assertNull($table->find()->last());
  860. }
  861. /**
  862. * Test that the typemaps used in function expressions
  863. * create the correct results.
  864. *
  865. * @return void
  866. */
  867. public function testTypemapInFunctions()
  868. {
  869. $table = TableRegistry::get('Comments');
  870. $table->updateAll(['published' => null], ['1 = 1']);
  871. $query = $table->find();
  872. $query->select([
  873. 'id',
  874. 'coalesced' => $query->func()->coalesce(
  875. ['published' => 'literal', -1],
  876. ['integer']
  877. )
  878. ]);
  879. $result = $query->all()->first();
  880. $this->assertSame(
  881. '-1',
  882. $result['coalesced'],
  883. 'Output values for functions are not cast yet.'
  884. );
  885. }
  886. /**
  887. * Test that contain queries map types correctly.
  888. *
  889. * @return void
  890. */
  891. public function testBooleanConditionsInContain()
  892. {
  893. $table = TableRegistry::get('Articles');
  894. $table->belongsToMany('Tags', [
  895. 'foreignKey' => 'article_id',
  896. 'associationForeignKey' => 'tag_id',
  897. 'through' => 'SpecialTags'
  898. ]);
  899. $query = $table->find()
  900. ->contain(['Tags' => function ($q) {
  901. return $q->where(['SpecialTags.highlighted_time >' => new Time('2014-06-01 00:00:00')]);
  902. }])
  903. ->where(['Articles.id' => 2]);
  904. $result = $query->first();
  905. $this->assertEquals(2, $result->id);
  906. $this->assertNotEmpty($result->tags, 'Missing tags');
  907. $this->assertNotEmpty($result->tags[0]->_joinData, 'Missing join data');
  908. }
  909. /**
  910. * Test that contain queries map types correctly.
  911. *
  912. * @return void
  913. */
  914. public function testComplexTypesInJoinedWhere()
  915. {
  916. $table = TableRegistry::get('Users');
  917. $table->hasOne('Comments', [
  918. 'foreignKey' => 'user_id',
  919. ]);
  920. $query = $table->find()
  921. ->contain('Comments')
  922. ->where([
  923. 'Comments.updated >' => new \DateTime('2007-03-18 10:55:00')
  924. ]);
  925. $result = $query->first();
  926. $this->assertNotEmpty($result);
  927. $this->assertInstanceOf('Cake\I18n\Time', $result->comment->updated);
  928. }
  929. /**
  930. * Test that nested contain queries map types correctly.
  931. *
  932. * @return void
  933. */
  934. public function testComplexNestedTypesInJoinedWhere()
  935. {
  936. $table = TableRegistry::get('Users');
  937. $table->hasOne('Comments', [
  938. 'foreignKey' => 'user_id',
  939. ]);
  940. $table->Comments->belongsTo('Articles');
  941. $table->Comments->Articles->belongsTo('Authors', [
  942. 'className' => 'Users',
  943. 'foreignKey' => 'author_id'
  944. ]);
  945. $query = $table->find()
  946. ->contain('Comments.Articles.Authors')
  947. ->where([
  948. 'Authors.created >' => new \DateTime('2007-03-17 01:16:00')
  949. ]);
  950. $result = $query->first();
  951. $this->assertNotEmpty($result);
  952. $this->assertInstanceOf('Cake\I18n\Time', $result->comment->article->author->updated);
  953. }
  954. /**
  955. * Tests that it is possible to use matching with dot notation
  956. * even when part of the part of the path in the dot notation is
  957. * shared for two different calls
  958. *
  959. * @return void
  960. */
  961. public function testDotNotationNotOverride()
  962. {
  963. $table = TableRegistry::get('Comments');
  964. $articles = $table->belongsTo('Articles');
  965. $specialTags = $articles->hasMany('SpecialTags');
  966. $specialTags->belongsTo('Authors');
  967. $specialTags->belongsTo('Tags');
  968. $results = $table
  969. ->find()
  970. ->select(['name' => 'Authors.name', 'tag' => 'Tags.name'])
  971. ->matching('Articles.SpecialTags.Tags')
  972. ->matching('Articles.SpecialTags.Authors', function ($q) {
  973. return $q->where(['Authors.id' => 2]);
  974. })
  975. ->distinct()
  976. ->hydrate(false)
  977. ->toArray();
  978. $this->assertEquals([['name' => 'nate', 'tag' => 'tag1']], $results);
  979. }
  980. /**
  981. * Test expression based ordering with unions.
  982. *
  983. * @return void
  984. */
  985. public function testComplexOrderWithUnion()
  986. {
  987. $table = TableRegistry::get('Comments');
  988. $query = $table->find();
  989. $inner = $table->find()
  990. ->select(['content' => 'comment'])
  991. ->where(['id >' => 3]);
  992. $inner2 = $table->find()
  993. ->select(['content' => 'comment'])
  994. ->where(['id <' => 3]);
  995. $order = $query->func()->concat(['content' => 'literal', 'test']);
  996. $query->select(['inside.content'])
  997. ->from(['inside' => $inner->unionAll($inner2)])
  998. ->orderAsc($order);
  999. $results = $query->toArray();
  1000. $this->assertCount(5, $results);
  1001. }
  1002. }