QueryRegressionTest.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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. $result = $articles->find()->contain(['Tags'])->first();
  179. $sub = $articles->Tags->find()->select(['id'])->matching('Articles', function ($q) use ($result) {
  180. return $q->where(['Articles.id' => 1]);
  181. });
  182. $query = $articles->Tags->find()->where(['id NOT IN' => $sub]);
  183. $this->assertEquals(1, $query->count());
  184. }
  185. /**
  186. * Returns an array with the saving strategies for a belongsTo association
  187. *
  188. * @return array
  189. */
  190. public function strategyProvider() {
  191. return [['append', 'replace']];
  192. }
  193. /**
  194. * Test for https://github.com/cakephp/cakephp/issues/3677 and
  195. * https://github.com/cakephp/cakephp/issues/3714
  196. *
  197. * Checks that only relevant associations are passed when saving _joinData
  198. * Tests that _joinData can also save deeper associations
  199. *
  200. * @dataProvider strategyProvider
  201. * @param string $strategy
  202. * @return void
  203. */
  204. public function testBelongsToManyDeepSave($strategy) {
  205. $articles = TableRegistry::get('Articles');
  206. $articles->belongsToMany('Highlights', [
  207. 'className' => 'TestApp\Model\Table\TagsTable',
  208. 'foreignKey' => 'article_id',
  209. 'targetForeignKey' => 'tag_id',
  210. 'through' => 'SpecialTags',
  211. 'saveStrategy' => $strategy
  212. ]);
  213. $articles->Highlights->junction()->belongsTo('Authors');
  214. $articles->Highlights->hasOne('Authors', [
  215. 'foreignKey' => 'id'
  216. ]);
  217. $entity = $articles->get(2, ['contain' => ['Highlights']]);
  218. $data = [
  219. 'highlights' => [
  220. [
  221. 'name' => 'New Special Tag',
  222. '_joinData' => [
  223. 'highlighted' => true,
  224. 'highlighted_time' => '2014-06-01 10:10:00',
  225. 'author' => [
  226. 'name' => 'mariano'
  227. ]
  228. ],
  229. 'author' => ['name' => 'mark']
  230. ]
  231. ]
  232. ];
  233. $options = [
  234. 'associated' => [
  235. 'Highlights._joinData.Authors', 'Highlights.Authors'
  236. ]
  237. ];
  238. $entity = $articles->patchEntity($entity, $data, $options);
  239. $articles->save($entity, $options);
  240. $entity = $articles->get(2, [
  241. 'contain' => [
  242. 'SpecialTags' => ['sort' => ['SpecialTags.id' => 'ASC']],
  243. 'SpecialTags.Authors',
  244. 'Highlights.Authors'
  245. ]
  246. ]);
  247. $this->assertEquals('mariano', end($entity->special_tags)->author->name);
  248. $this->assertEquals('mark', end($entity->highlights)->author->name);
  249. }
  250. /**
  251. * Tests that no exceptions are generated becuase of ambiguous column names in queries
  252. * during a save operation
  253. *
  254. * @see https://github.com/cakephp/cakephp/issues/3803
  255. * @return void
  256. */
  257. public function testSaveWithCallbacks() {
  258. $articles = TableRegistry::get('Articles');
  259. $articles->belongsTo('Authors');
  260. $articles->eventManager()->attach(function ($event, $query) {
  261. return $query->contain('Authors');
  262. }, 'Model.beforeFind');
  263. $article = $articles->newEntity();
  264. $article->title = 'Foo';
  265. $article->body = 'Bar';
  266. $this->assertSame($article, $articles->save($article));
  267. }
  268. /**
  269. * Test that save() works with entities containing expressions
  270. * as properties.
  271. *
  272. * @return void
  273. */
  274. public function testSaveWithExpressionProperty() {
  275. $articles = TableRegistry::get('Articles');
  276. $article = $articles->newEntity();
  277. $article->title = new \Cake\Database\Expression\QueryExpression("SELECT 'jose'");
  278. $this->assertSame($article, $articles->save($article));
  279. }
  280. /**
  281. * Tests that whe saving deep associations for a belongsToMany property,
  282. * data is not removed becuase of excesive associations filtering.
  283. *
  284. * @see https://github.com/cakephp/cakephp/issues/4009
  285. * @return void
  286. */
  287. public function testBelongsToManyDeepSave2() {
  288. $articles = TableRegistry::get('Articles');
  289. $articles->belongsToMany('Highlights', [
  290. 'className' => 'TestApp\Model\Table\TagsTable',
  291. 'foreignKey' => 'article_id',
  292. 'targetForeignKey' => 'tag_id',
  293. 'through' => 'SpecialTags',
  294. ]);
  295. $articles->Highlights->hasMany('TopArticles', [
  296. 'className' => 'TestApp\Model\Table\ArticlesTable',
  297. 'foreignKey' => 'author_id',
  298. ]);
  299. $entity = $articles->get(2, ['contain' => ['Highlights']]);
  300. $data = [
  301. 'highlights' => [
  302. [
  303. 'name' => 'New Special Tag',
  304. '_joinData' => [
  305. 'highlighted' => true,
  306. 'highlighted_time' => '2014-06-01 10:10:00',
  307. ],
  308. 'top_articles' => [
  309. ['title' => 'First top article'],
  310. ['title' => 'Second top article'],
  311. ]
  312. ]
  313. ]
  314. ];
  315. $options = [
  316. 'associated' => [
  317. 'Highlights._joinData', 'Highlights.TopArticles'
  318. ]
  319. ];
  320. $entity = $articles->patchEntity($entity, $data, $options);
  321. $articles->save($entity, $options);
  322. $entity = $articles->get(2, [
  323. 'contain' => [
  324. 'Highlights.TopArticles'
  325. ]
  326. ]);
  327. $highlights = $entity->highlights[0];
  328. $this->assertEquals('First top article', $highlights->top_articles[0]->title);
  329. $this->assertEquals('Second top article', $highlights->top_articles[1]->title);
  330. $this->assertEquals(
  331. new Time('2014-06-01 10:10:00'),
  332. $highlights->_joinData->highlighted_time
  333. );
  334. }
  335. /**
  336. * An integration test that spot checks that associations use the
  337. * correct alias names to generate queries.
  338. *
  339. * @return void
  340. */
  341. public function testPluginAssociationQueryGeneration() {
  342. Plugin::load('TestPlugin');
  343. $articles = TableRegistry::get('Articles');
  344. $articles->hasMany('TestPlugin.Comments');
  345. $articles->belongsTo('TestPlugin.Authors');
  346. $result = $articles->find()
  347. ->where(['Articles.id' => 2])
  348. ->contain(['Comments', 'Authors'])
  349. ->first();
  350. $this->assertNotEmpty(
  351. $result->comments[0]->id,
  352. 'No SQL error and comment exists.'
  353. );
  354. $this->assertNotEmpty(
  355. $result->author->id,
  356. 'No SQL error and author exists.'
  357. );
  358. }
  359. /**
  360. * Tests that loading associations having the same alias in the
  361. * joinable associations chain is not sensitive to the order in which
  362. * the associations are selected.
  363. *
  364. * @see https://github.com/cakephp/cakephp/issues/4454
  365. * @return void
  366. */
  367. public function testAssociationChainOrder() {
  368. $articles = TableRegistry::get('Articles');
  369. $articles->belongsTo('Authors');
  370. $articles->hasOne('ArticlesTags');
  371. $articlesTags = TableRegistry::get('ArticlesTags');
  372. $articlesTags->belongsTo('Authors', [
  373. 'foreignKey' => 'tag_id'
  374. ]);
  375. $resultA = $articles->find()
  376. ->contain(['ArticlesTags.Authors', 'Authors'])
  377. ->first();
  378. $resultB = $articles->find()
  379. ->contain(['Authors', 'ArticlesTags.Authors'])
  380. ->first();
  381. $this->assertEquals($resultA, $resultB);
  382. $this->assertNotEmpty($resultA->author);
  383. $this->assertNotEmpty($resultA->articles_tag->author);
  384. }
  385. /**
  386. * Test that offset/limit are elided from subquery loads.
  387. *
  388. * @return void
  389. */
  390. public function testAssociationSubQueryNoOffset() {
  391. $table = TableRegistry::get('Articles');
  392. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  393. $table->locale('eng');
  394. $query = $table->find('translations')->limit(10)->offset(1);
  395. $result = $query->toArray();
  396. $this->assertCount(2, $result);
  397. }
  398. /**
  399. * Tests that using the subquery strategy in a deep assotiatin returns the right results
  400. *
  401. * @see https://github.com/cakephp/cakephp/issues/4484
  402. * @return void
  403. */
  404. public function testDeepBelongsToManySubqueryStrategy() {
  405. $table = TableRegistry::get('Authors');
  406. $table->hasMany('Articles');
  407. $table->Articles->belongsToMany('Tags', [
  408. 'strategy' => 'subquery'
  409. ]);
  410. $table->Articles->Tags->junction();
  411. $result = $table->find()->contain(['Articles.Tags'])->toArray();
  412. $this->assertEquals(
  413. ['tag1', 'tag3'],
  414. collection($result[2]->articles[0]->tags)->extract('name')->toArray()
  415. );
  416. }
  417. /**
  418. * Tests that getting the count of a query having containments return
  419. * the correct results
  420. *
  421. * @see https://github.com/cakephp/cakephp/issues/4511
  422. * @return void
  423. */
  424. public function testCountWithContain() {
  425. $table = TableRegistry::get('Articles');
  426. $table->belongsTo('Authors', ['joinType' => 'inner']);
  427. $count = $table
  428. ->find()
  429. ->contain(['Authors' => function ($q) {
  430. return $q->where(['Authors.id' => 1]);
  431. }])
  432. ->count();
  433. $this->assertEquals(2, $count);
  434. }
  435. /**
  436. * Test that deep containments don't generate empty entities for
  437. * intermediary relations.
  438. *
  439. * @return void
  440. */
  441. public function testContainNoEmptyAssociatedObjects() {
  442. $comments = TableRegistry::get('Comments');
  443. $comments->belongsTo('Users');
  444. $users = TableRegistry::get('Users');
  445. $users->hasMany('Articles', [
  446. 'foreignKey' => 'author_id'
  447. ]);
  448. $comments->updateAll(['user_id' => 99], ['id' => 1]);
  449. $result = $comments->find()
  450. ->contain(['Users'])
  451. ->where(['Comments.id' => 1])
  452. ->first();
  453. $this->assertNull($result->user, 'No record should be null.');
  454. $result = $comments->find()
  455. ->contain(['Users', 'Users.Articles'])
  456. ->where(['Comments.id' => 1])
  457. ->first();
  458. $this->assertNull($result->user, 'No record should be null.');
  459. }
  460. }