QueryRegressionTest.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  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. * Fixture to be used
  29. *
  30. * @var array
  31. */
  32. public $fixtures = [
  33. 'core.users',
  34. 'core.articles',
  35. 'core.comments',
  36. 'core.tags',
  37. 'core.articles_tags',
  38. 'core.authors',
  39. 'core.special_tags',
  40. 'core.translates',
  41. ];
  42. /**
  43. * Tear down
  44. *
  45. * @return void
  46. */
  47. public function tearDown() {
  48. parent::tearDown();
  49. TableRegistry::clear();
  50. }
  51. /**
  52. * Test for https://github.com/cakephp/cakephp/issues/3087
  53. *
  54. * @return void
  55. */
  56. public function testSelectTimestampColumn() {
  57. $table = TableRegistry::get('users');
  58. $user = $table->find()->where(['id' => 1])->first();
  59. $this->assertEquals(new Time('2007-03-17 01:16:23'), $user->created);
  60. $this->assertEquals(new Time('2007-03-17 01:18:31'), $user->updated);
  61. }
  62. /**
  63. * Tests that EagerLoader does not try to create queries for associations having no
  64. * keys to compare against
  65. *
  66. * @return void
  67. */
  68. public function testEagerLoadingFromEmptyResults() {
  69. $table = TableRegistry::get('Articles');
  70. $table->belongsToMany('ArticlesTags');
  71. $results = $table->find()->where(['id >' => 100])->contain('ArticlesTags')->toArray();
  72. $this->assertEmpty($results);
  73. }
  74. /**
  75. * Tests that duplicate aliases in contain() can be used, even when they would
  76. * naturally be attached to the query instead of eagerly loaded. What should
  77. * happen here is that One of the duplicates will be changed to be loaded using
  78. * an extra query, but yielding the same results
  79. *
  80. * @return void
  81. */
  82. public function testDuplicateAttachableAliases() {
  83. TableRegistry::get('Stuff', ['table' => 'tags']);
  84. TableRegistry::get('Things', ['table' => 'articles_tags']);
  85. $table = TableRegistry::get('Articles');
  86. $table->belongsTo('Authors');
  87. $table->hasOne('Things', ['propertyName' => 'articles_tag']);
  88. $table->Authors->target()->hasOne('Stuff', [
  89. 'foreignKey' => 'id',
  90. 'propertyName' => 'favorite_tag'
  91. ]);
  92. $table->Things->target()->belongsTo('Stuff', [
  93. 'foreignKey' => 'tag_id',
  94. 'propertyName' => 'foo'
  95. ]);
  96. $results = $table->find()
  97. ->contain(['Authors.Stuff', 'Things.Stuff'])
  98. ->order(['Articles.id' => 'ASC'])
  99. ->toArray();
  100. $this->assertEquals(1, $results[0]->articles_tag->foo->id);
  101. $this->assertEquals(1, $results[0]->author->favorite_tag->id);
  102. $this->assertEquals(2, $results[1]->articles_tag->foo->id);
  103. $this->assertEquals(1, $results[0]->author->favorite_tag->id);
  104. $this->assertEquals(1, $results[2]->articles_tag->foo->id);
  105. $this->assertEquals(3, $results[2]->author->favorite_tag->id);
  106. $this->assertEquals(3, $results[3]->articles_tag->foo->id);
  107. $this->assertEquals(3, $results[3]->author->favorite_tag->id);
  108. }
  109. /**
  110. * Test for https://github.com/cakephp/cakephp/issues/3410
  111. *
  112. * @return void
  113. */
  114. public function testNullableTimeColumn() {
  115. $table = TableRegistry::get('users');
  116. $entity = $table->newEntity(['username' => 'derp', 'created' => null]);
  117. $this->assertSame($entity, $table->save($entity));
  118. $this->assertNull($entity->created);
  119. }
  120. /**
  121. * Test for https://github.com/cakephp/cakephp/issues/3626
  122. *
  123. * Checks that join data is actually created and not tried to be updated every time
  124. * @return void
  125. */
  126. public function testCreateJointData() {
  127. $articles = TableRegistry::get('Articles');
  128. $articles->belongsToMany('Highlights', [
  129. 'className' => 'TestApp\Model\Table\TagsTable',
  130. 'foreignKey' => 'article_id',
  131. 'targetForeignKey' => 'tag_id',
  132. 'through' => 'SpecialTags'
  133. ]);
  134. $entity = $articles->get(2);
  135. $data = [
  136. 'id' => 2,
  137. 'highlights' => [
  138. [
  139. 'name' => 'New Special Tag',
  140. '_joinData' => ['highlighted' => true, 'highlighted_time' => '2014-06-01 10:10:00']
  141. ]
  142. ]
  143. ];
  144. $entity = $articles->patchEntity($entity, $data, ['Highlights._joinData']);
  145. $articles->save($entity);
  146. $entity = $articles->get(2, ['contain' => ['Highlights']]);
  147. $this->assertEquals(4, $entity->highlights[0]->_joinData->tag_id);
  148. $this->assertEquals('2014-06-01', $entity->highlights[0]->_joinData->highlighted_time->format('Y-m-d'));
  149. }
  150. /**
  151. * Tests that the junction table instance taken from both sides of a belongsToMany
  152. * relationship is actually the same object.
  153. *
  154. * @return void
  155. */
  156. public function testReciprocalBelongsToMany() {
  157. $articles = TableRegistry::get('Articles');
  158. $tags = TableRegistry::get('Tags');
  159. $articles->belongsToMany('Tags');
  160. $tags->belongsToMany('Articles');
  161. $left = $articles->Tags->junction();
  162. $right = $tags->Articles->junction();
  163. $this->assertSame($left, $right);
  164. }
  165. /**
  166. * Test for https://github.com/cakephp/cakephp/issues/4253
  167. *
  168. * Makes sure that the belongsToMany association is not overwritten with conflicting information
  169. * by any of the sides when the junction() function is invoked
  170. *
  171. * @return void
  172. */
  173. public function testReciprocalBelongsToMany2() {
  174. $articles = TableRegistry::get('Articles');
  175. $tags = TableRegistry::get('Tags');
  176. $articles->belongsToMany('Tags');
  177. $tags->belongsToMany('Articles');
  178. $sub = $articles->Tags->find()->select(['id'])->matching('Articles', function ($q) {
  179. return $q->where(['Articles.id' => 1]);
  180. });
  181. $query = $articles->Tags->find()->where(['id NOT IN' => $sub]);
  182. $this->assertEquals(1, $query->count());
  183. }
  184. /**
  185. * Returns an array with the saving strategies for a belongsTo association
  186. *
  187. * @return array
  188. */
  189. public function strategyProvider() {
  190. return [['append', 'replace']];
  191. }
  192. /**
  193. * Test for https://github.com/cakephp/cakephp/issues/3677 and
  194. * https://github.com/cakephp/cakephp/issues/3714
  195. *
  196. * Checks that only relevant associations are passed when saving _joinData
  197. * Tests that _joinData can also save deeper associations
  198. *
  199. * @dataProvider strategyProvider
  200. * @param string $strategy
  201. * @return void
  202. */
  203. public function testBelongsToManyDeepSave($strategy) {
  204. $articles = TableRegistry::get('Articles');
  205. $articles->belongsToMany('Highlights', [
  206. 'className' => 'TestApp\Model\Table\TagsTable',
  207. 'foreignKey' => 'article_id',
  208. 'targetForeignKey' => 'tag_id',
  209. 'through' => 'SpecialTags',
  210. 'saveStrategy' => $strategy
  211. ]);
  212. $articles->Highlights->junction()->belongsTo('Authors');
  213. $articles->Highlights->hasOne('Authors', [
  214. 'foreignKey' => 'id'
  215. ]);
  216. $entity = $articles->get(2, ['contain' => ['Highlights']]);
  217. $data = [
  218. 'highlights' => [
  219. [
  220. 'name' => 'New Special Tag',
  221. '_joinData' => [
  222. 'highlighted' => true,
  223. 'highlighted_time' => '2014-06-01 10:10:00',
  224. 'author' => [
  225. 'name' => 'mariano'
  226. ]
  227. ],
  228. 'author' => ['name' => 'mark']
  229. ]
  230. ]
  231. ];
  232. $options = [
  233. 'associated' => [
  234. 'Highlights._joinData.Authors', 'Highlights.Authors'
  235. ]
  236. ];
  237. $entity = $articles->patchEntity($entity, $data, $options);
  238. $articles->save($entity, $options);
  239. $entity = $articles->get(2, [
  240. 'contain' => [
  241. 'SpecialTags' => ['sort' => ['SpecialTags.id' => 'ASC']],
  242. 'SpecialTags.Authors',
  243. 'Highlights.Authors'
  244. ]
  245. ]);
  246. $this->assertEquals('mariano', end($entity->special_tags)->author->name);
  247. $this->assertEquals('mark', end($entity->highlights)->author->name);
  248. }
  249. /**
  250. * Tests that no exceptions are generated becuase of ambiguous column names in queries
  251. * during a save operation
  252. *
  253. * @see https://github.com/cakephp/cakephp/issues/3803
  254. * @return void
  255. */
  256. public function testSaveWithCallbacks() {
  257. $articles = TableRegistry::get('Articles');
  258. $articles->belongsTo('Authors');
  259. $articles->eventManager()->attach(function ($event, $query) {
  260. return $query->contain('Authors');
  261. }, 'Model.beforeFind');
  262. $article = $articles->newEntity();
  263. $article->title = 'Foo';
  264. $article->body = 'Bar';
  265. $this->assertSame($article, $articles->save($article));
  266. }
  267. /**
  268. * Test that save() works with entities containing expressions
  269. * as properties.
  270. *
  271. * @return void
  272. */
  273. public function testSaveWithExpressionProperty() {
  274. $articles = TableRegistry::get('Articles');
  275. $article = $articles->newEntity();
  276. $article->title = new \Cake\Database\Expression\QueryExpression("SELECT 'jose'");
  277. $this->assertSame($article, $articles->save($article));
  278. }
  279. /**
  280. * Tests that whe saving deep associations for a belongsToMany property,
  281. * data is not removed becuase of excesive associations filtering.
  282. *
  283. * @see https://github.com/cakephp/cakephp/issues/4009
  284. * @return void
  285. */
  286. public function testBelongsToManyDeepSave2() {
  287. $articles = TableRegistry::get('Articles');
  288. $articles->belongsToMany('Highlights', [
  289. 'className' => 'TestApp\Model\Table\TagsTable',
  290. 'foreignKey' => 'article_id',
  291. 'targetForeignKey' => 'tag_id',
  292. 'through' => 'SpecialTags',
  293. ]);
  294. $articles->Highlights->hasMany('TopArticles', [
  295. 'className' => 'TestApp\Model\Table\ArticlesTable',
  296. 'foreignKey' => 'author_id',
  297. ]);
  298. $entity = $articles->get(2, ['contain' => ['Highlights']]);
  299. $data = [
  300. 'highlights' => [
  301. [
  302. 'name' => 'New Special Tag',
  303. '_joinData' => [
  304. 'highlighted' => true,
  305. 'highlighted_time' => '2014-06-01 10:10:00',
  306. ],
  307. 'top_articles' => [
  308. ['title' => 'First top article'],
  309. ['title' => 'Second top article'],
  310. ]
  311. ]
  312. ]
  313. ];
  314. $options = [
  315. 'associated' => [
  316. 'Highlights._joinData', 'Highlights.TopArticles'
  317. ]
  318. ];
  319. $entity = $articles->patchEntity($entity, $data, $options);
  320. $articles->save($entity, $options);
  321. $entity = $articles->get(2, [
  322. 'contain' => [
  323. 'Highlights.TopArticles'
  324. ]
  325. ]);
  326. $highlights = $entity->highlights[0];
  327. $this->assertEquals('First top article', $highlights->top_articles[0]->title);
  328. $this->assertEquals('Second top article', $highlights->top_articles[1]->title);
  329. $this->assertEquals(
  330. new Time('2014-06-01 10:10:00'),
  331. $highlights->_joinData->highlighted_time
  332. );
  333. }
  334. /**
  335. * An integration test that spot checks that associations use the
  336. * correct alias names to generate queries.
  337. *
  338. * @return void
  339. */
  340. public function testPluginAssociationQueryGeneration() {
  341. Plugin::load('TestPlugin');
  342. $articles = TableRegistry::get('Articles');
  343. $articles->hasMany('TestPlugin.Comments');
  344. $articles->belongsTo('TestPlugin.Authors');
  345. $result = $articles->find()
  346. ->where(['Articles.id' => 2])
  347. ->contain(['Comments', 'Authors'])
  348. ->first();
  349. $this->assertNotEmpty(
  350. $result->comments[0]->id,
  351. 'No SQL error and comment exists.'
  352. );
  353. $this->assertNotEmpty(
  354. $result->author->id,
  355. 'No SQL error and author exists.'
  356. );
  357. }
  358. /**
  359. * Tests that loading associations having the same alias in the
  360. * joinable associations chain is not sensitive to the order in which
  361. * the associations are selected.
  362. *
  363. * @see https://github.com/cakephp/cakephp/issues/4454
  364. * @return void
  365. */
  366. public function testAssociationChainOrder() {
  367. $articles = TableRegistry::get('Articles');
  368. $articles->belongsTo('Authors');
  369. $articles->hasOne('ArticlesTags');
  370. $articlesTags = TableRegistry::get('ArticlesTags');
  371. $articlesTags->belongsTo('Authors', [
  372. 'foreignKey' => 'tag_id'
  373. ]);
  374. $resultA = $articles->find()
  375. ->contain(['ArticlesTags.Authors', 'Authors'])
  376. ->first();
  377. $resultB = $articles->find()
  378. ->contain(['Authors', 'ArticlesTags.Authors'])
  379. ->first();
  380. $this->assertEquals($resultA, $resultB);
  381. $this->assertNotEmpty($resultA->author);
  382. $this->assertNotEmpty($resultA->articles_tag->author);
  383. }
  384. /**
  385. * Test that offset/limit are elided from subquery loads.
  386. *
  387. * @return void
  388. */
  389. public function testAssociationSubQueryNoOffset() {
  390. $table = TableRegistry::get('Articles');
  391. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  392. $table->locale('eng');
  393. $query = $table->find('translations')->limit(10)->offset(1);
  394. $result = $query->toArray();
  395. $this->assertCount(2, $result);
  396. }
  397. /**
  398. * Tests that using the subquery strategy in a deep assotiatin returns the right results
  399. *
  400. * @see https://github.com/cakephp/cakephp/issues/4484
  401. * @return void
  402. */
  403. public function testDeepBelongsToManySubqueryStrategy() {
  404. $table = TableRegistry::get('Authors');
  405. $table->hasMany('Articles');
  406. $table->Articles->belongsToMany('Tags', [
  407. 'strategy' => 'subquery'
  408. ]);
  409. $table->Articles->Tags->junction();
  410. $result = $table->find()->contain(['Articles.Tags'])->toArray();
  411. $this->assertEquals(
  412. ['tag1', 'tag3'],
  413. collection($result[2]->articles[0]->tags)->extract('name')->toArray()
  414. );
  415. }
  416. /**
  417. * Tests that getting the count of a query having containments return
  418. * the correct results
  419. *
  420. * @see https://github.com/cakephp/cakephp/issues/4511
  421. * @return void
  422. */
  423. public function testCountWithContain() {
  424. $table = TableRegistry::get('Articles');
  425. $table->belongsTo('Authors', ['joinType' => 'inner']);
  426. $count = $table
  427. ->find()
  428. ->contain(['Authors' => function ($q) {
  429. return $q->where(['Authors.id' => 1]);
  430. }])
  431. ->count();
  432. $this->assertEquals(2, $count);
  433. }
  434. /**
  435. * Test that deep containments don't generate empty entities for
  436. * intermediary relations.
  437. *
  438. * @return void
  439. */
  440. public function testContainNoEmptyAssociatedObjects() {
  441. $comments = TableRegistry::get('Comments');
  442. $comments->belongsTo('Users');
  443. $users = TableRegistry::get('Users');
  444. $users->hasMany('Articles', [
  445. 'foreignKey' => 'author_id'
  446. ]);
  447. $comments->updateAll(['user_id' => 99], ['id' => 1]);
  448. $result = $comments->find()
  449. ->contain(['Users'])
  450. ->where(['Comments.id' => 1])
  451. ->first();
  452. $this->assertNull($result->user, 'No record should be null.');
  453. $result = $comments->find()
  454. ->contain(['Users', 'Users.Articles'])
  455. ->where(['Comments.id' => 1])
  456. ->first();
  457. $this->assertNull($result->user, 'No record should be null.');
  458. }
  459. /**
  460. * Tests that using a comparison expression inside an OR condition works
  461. *
  462. * @see https://github.com/cakephp/cakephp/issues/5081
  463. * @return void
  464. */
  465. public function testOrConditionsWithExpression() {
  466. $table = TableRegistry::get('Articles');
  467. $query = $table->find();
  468. $query->where([
  469. 'OR' => [
  470. new \Cake\Database\Expression\Comparison('id', 1, 'integer', '>'),
  471. new \Cake\Database\Expression\Comparison('id', 3, 'integer', '<')
  472. ]
  473. ]);
  474. $results = $query->toArray();
  475. $this->assertCount(3, $results);
  476. }
  477. /**
  478. * Tests that calling count on a query having a union works correctly
  479. *
  480. * @see https://github.com/cakephp/cakephp/issues/5107
  481. * @return void
  482. */
  483. public function testCountWithUnionQuery() {
  484. $table = TableRegistry::get('Articles');
  485. $query = $table->find()->where(['id' => 1]);
  486. $query2 = $table->find()->where(['id' => 2]);
  487. $query->union($query2);
  488. $this->assertEquals(2, $query->count());
  489. }
  490. /**
  491. * Integration test when selecting no fields on the primary table.
  492. *
  493. * @return void
  494. */
  495. public function testSelectNoFieldsOnPrimaryAlias() {
  496. $table = TableRegistry::get('Articles');
  497. $table->belongsTo('Users');
  498. $query = $table->find()
  499. ->select(['Users__id' => 'id']);
  500. $results = $query->toArray();
  501. $this->assertCount(3, $results);
  502. }
  503. }