QueryRegressionTest.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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.user',
  34. 'core.article',
  35. 'core.comment',
  36. 'core.tag',
  37. 'core.articles_tag',
  38. 'core.author',
  39. 'core.special_tag',
  40. 'core.translate',
  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. ->toArray();
  99. $this->assertEquals(1, $results[0]->articles_tag->foo->id);
  100. $this->assertEquals(1, $results[0]->author->favorite_tag->id);
  101. $this->assertEquals(2, $results[1]->articles_tag->foo->id);
  102. $this->assertEquals(1, $results[0]->author->favorite_tag->id);
  103. $this->assertEquals(1, $results[2]->articles_tag->foo->id);
  104. $this->assertEquals(3, $results[2]->author->favorite_tag->id);
  105. $this->assertEquals(3, $results[3]->articles_tag->foo->id);
  106. $this->assertEquals(3, $results[3]->author->favorite_tag->id);
  107. }
  108. /**
  109. * Test for https://github.com/cakephp/cakephp/issues/3410
  110. *
  111. * @return void
  112. */
  113. public function testNullableTimeColumn() {
  114. $table = TableRegistry::get('users');
  115. $entity = $table->newEntity(['username' => 'derp', 'created' => null]);
  116. $this->assertSame($entity, $table->save($entity));
  117. $this->assertNull($entity->created);
  118. }
  119. /**
  120. * Test for https://github.com/cakephp/cakephp/issues/3626
  121. *
  122. * Checks that join data is actually created and not tried to be updated every time
  123. * @return void
  124. */
  125. public function testCreateJointData() {
  126. $articles = TableRegistry::get('Articles');
  127. $articles->belongsToMany('Highlights', [
  128. 'className' => 'TestApp\Model\Table\TagsTable',
  129. 'foreignKey' => 'article_id',
  130. 'targetForeignKey' => 'tag_id',
  131. 'through' => 'SpecialTags'
  132. ]);
  133. $entity = $articles->get(2);
  134. $data = [
  135. 'id' => 2,
  136. 'highlights' => [
  137. [
  138. 'name' => 'New Special Tag',
  139. '_joinData' => ['highlighted' => true, 'highlighted_time' => '2014-06-01 10:10:00']
  140. ]
  141. ]
  142. ];
  143. $entity = $articles->patchEntity($entity, $data, ['Highlights._joinData']);
  144. $articles->save($entity);
  145. $entity = $articles->get(2, ['contain' => ['Highlights']]);
  146. $this->assertEquals(4, $entity->highlights[0]->_joinData->tag_id);
  147. $this->assertEquals('2014-06-01', $entity->highlights[0]->_joinData->highlighted_time->format('Y-m-d'));
  148. }
  149. /**
  150. * Tests that the junction table instance taken from both sides of a belongsToMany
  151. * relationship is actually the same object.
  152. *
  153. * @return void
  154. */
  155. public function testReciprocalBelongsToMany() {
  156. $articles = TableRegistry::get('Articles');
  157. $tags = TableRegistry::get('Tags');
  158. $articles->belongsToMany('Tags');
  159. $tags->belongsToMany('Articles');
  160. $left = $articles->Tags->junction();
  161. $right = $tags->Articles->junction();
  162. $this->assertSame($left, $right);
  163. }
  164. /**
  165. * Test for https://github.com/cakephp/cakephp/issues/4253
  166. *
  167. * Makes sure that the belongsToMany association is not overwritten with conflicting information
  168. * by any of the sides when the junction() function is invoked
  169. *
  170. * @return void
  171. */
  172. public function testReciprocalBelongsToMany2() {
  173. $articles = TableRegistry::get('Articles');
  174. $tags = TableRegistry::get('Tags');
  175. $articles->belongsToMany('Tags');
  176. $tags->belongsToMany('Articles');
  177. $result = $articles->find()->contain(['Tags'])->first();
  178. $sub = $articles->Tags->find()->select(['id'])->matching('Articles', function($q) use ($result) {
  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. * Tests that whe saving deep associations for a belongsToMany property,
  269. * data is not removed becuase of excesive associations filtering.
  270. *
  271. * @see https://github.com/cakephp/cakephp/issues/4009
  272. * @return void
  273. */
  274. public function testBelongsToManyDeepSave2() {
  275. $articles = TableRegistry::get('Articles');
  276. $articles->belongsToMany('Highlights', [
  277. 'className' => 'TestApp\Model\Table\TagsTable',
  278. 'foreignKey' => 'article_id',
  279. 'targetForeignKey' => 'tag_id',
  280. 'through' => 'SpecialTags',
  281. ]);
  282. $articles->Highlights->hasMany('TopArticles', [
  283. 'className' => 'TestApp\Model\Table\ArticlesTable',
  284. 'foreignKey' => 'author_id',
  285. ]);
  286. $entity = $articles->get(2, ['contain' => ['Highlights']]);
  287. $data = [
  288. 'highlights' => [
  289. [
  290. 'name' => 'New Special Tag',
  291. '_joinData' => [
  292. 'highlighted' => true,
  293. 'highlighted_time' => '2014-06-01 10:10:00',
  294. ],
  295. 'top_articles' => [
  296. ['title' => 'First top article'],
  297. ['title' => 'Second top article'],
  298. ]
  299. ]
  300. ]
  301. ];
  302. $options = [
  303. 'associated' => [
  304. 'Highlights._joinData', 'Highlights.TopArticles'
  305. ]
  306. ];
  307. $entity = $articles->patchEntity($entity, $data, $options);
  308. $articles->save($entity, $options);
  309. $entity = $articles->get(2, [
  310. 'contain' => [
  311. 'Highlights.TopArticles'
  312. ]
  313. ]);
  314. $highlights = $entity->highlights[0];
  315. $this->assertEquals('First top article', $highlights->top_articles[0]->title);
  316. $this->assertEquals('Second top article', $highlights->top_articles[1]->title);
  317. $this->assertEquals(
  318. new Time('2014-06-01 10:10:00'),
  319. $highlights->_joinData->highlighted_time
  320. );
  321. }
  322. /**
  323. * An integration test that spot checks that associations use the
  324. * correct alias names to generate queries.
  325. *
  326. * @return void
  327. */
  328. public function testPluginAssociationQueryGeneration() {
  329. Plugin::load('TestPlugin');
  330. $articles = TableRegistry::get('Articles');
  331. $articles->hasMany('TestPlugin.Comments');
  332. $articles->belongsTo('TestPlugin.Authors');
  333. $result = $articles->find()
  334. ->where(['Articles.id' => 2])
  335. ->contain(['Comments', 'Authors'])
  336. ->first();
  337. $this->assertNotEmpty(
  338. $result->comments[0]->id,
  339. 'No SQL error and comment exists.'
  340. );
  341. $this->assertNotEmpty(
  342. $result->author->id,
  343. 'No SQL error and author exists.'
  344. );
  345. }
  346. /**
  347. * Tests that loading associations having the same alias in the
  348. * joinable associations chain is not sensitive to the order in which
  349. * the associations are selected.
  350. *
  351. * @see https://github.com/cakephp/cakephp/issues/4454
  352. * @return void
  353. */
  354. public function testAssociationChainOrder() {
  355. $articles = TableRegistry::get('Articles');
  356. $articles->belongsTo('Authors');
  357. $articles->hasOne('ArticlesTags');
  358. $articlesTags = TableRegistry::get('ArticlesTags');
  359. $articlesTags->belongsTo('Authors', [
  360. 'foreignKey' => 'tag_id'
  361. ]);
  362. $resultA = $articles->find()
  363. ->contain(['ArticlesTags.Authors', 'Authors'])
  364. ->first();
  365. $resultB = $articles->find()
  366. ->contain(['Authors', 'ArticlesTags.Authors'])
  367. ->first();
  368. $this->assertEquals($resultA, $resultB);
  369. $this->assertNotEmpty($resultA->author);
  370. $this->assertNotEmpty($resultA->articles_tag->author);
  371. }
  372. /**
  373. * Test that offset/limit are elided from subquery loads.
  374. *
  375. * @return void
  376. */
  377. public function testAssociationSubQueryNoOffset() {
  378. $table = TableRegistry::get('Articles');
  379. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  380. $table->locale('eng');
  381. $query = $table->find('translations')->limit(10)->offset(1);
  382. $result = $query->toArray();
  383. $this->assertCount(2, $result);
  384. }
  385. /**
  386. * Tests that using the subquery strategy in a deep assotiatin returns the right results
  387. *
  388. * @see https://github.com/cakephp/cakephp/issues/4484
  389. * @return void
  390. */
  391. public function testDeepBelongsToManySubqueryStrategy() {
  392. $table = TableRegistry::get('Authors');
  393. $table->hasMany('Articles');
  394. $table->Articles->belongsToMany('Tags', [
  395. 'strategy' => 'subquery'
  396. ]);
  397. $table->Articles->Tags->junction();
  398. $result = $table->find()->contain(['Articles.Tags'])->toArray();
  399. $this->assertEquals(
  400. ['tag1', 'tag3'],
  401. collection($result[2]->articles[0]->tags)->extract('name')->toArray()
  402. );
  403. }
  404. /**
  405. * Tests that getting the count of a query having containments return
  406. * the correct results
  407. *
  408. * @see https://github.com/cakephp/cakephp/issues/4511
  409. * @return void
  410. */
  411. public function testCountWithContain() {
  412. $table = TableRegistry::get('Articles');
  413. $table->belongsTo('Authors', ['joinType' => 'inner']);
  414. $count = $table
  415. ->find()
  416. ->contain(['Authors' => function($q) {
  417. return $q->where(['Authors.id' => 1]);
  418. }])
  419. ->count();
  420. $this->assertEquals(2, $count);
  421. }
  422. }