ResultSetTest.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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\Exception;
  18. use Cake\Datasource\ConnectionManager;
  19. use Cake\ORM\Entity;
  20. use Cake\ORM\ResultSet;
  21. use Cake\ORM\Table;
  22. use Cake\TestSuite\TestCase;
  23. use TestApp\Model\Entity\Article;
  24. /**
  25. * ResultSet test case.
  26. */
  27. class ResultSetTest extends TestCase
  28. {
  29. public $fixtures = ['core.Articles', 'core.Authors', 'core.Comments'];
  30. /**
  31. * setup
  32. *
  33. * @return void
  34. */
  35. public function setUp()
  36. {
  37. parent::setUp();
  38. $this->connection = ConnectionManager::get('test');
  39. $this->table = new Table([
  40. 'table' => 'articles',
  41. 'connection' => $this->connection,
  42. ]);
  43. $this->fixtureData = [
  44. ['id' => 1, 'author_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y'],
  45. ['id' => 2, 'author_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', 'published' => 'Y'],
  46. ['id' => 3, 'author_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', 'published' => 'Y'],
  47. ];
  48. }
  49. /**
  50. * Test that result sets can be rewound and re-used.
  51. *
  52. * @return void
  53. */
  54. public function testRewind()
  55. {
  56. $query = $this->table->find('all');
  57. $results = $query->all();
  58. $first = $second = [];
  59. foreach ($results as $result) {
  60. $first[] = $result;
  61. }
  62. foreach ($results as $result) {
  63. $second[] = $result;
  64. }
  65. $this->assertEquals($first, $second);
  66. }
  67. /**
  68. * Test that streaming results cannot be rewound
  69. *
  70. * @return void
  71. */
  72. public function testRewindStreaming()
  73. {
  74. $query = $this->table->find('all')->enableBufferedResults(false);
  75. $results = $query->all();
  76. $first = $second = [];
  77. foreach ($results as $result) {
  78. $first[] = $result;
  79. }
  80. $this->expectException(Exception::class);
  81. foreach ($results as $result) {
  82. $second[] = $result;
  83. }
  84. }
  85. /**
  86. * An integration test for testing serialize and unserialize features.
  87. *
  88. * Compare the results of a query with the results iterated, with
  89. * those of a different query that have been serialized/unserialized.
  90. *
  91. * @return void
  92. */
  93. public function testSerialization()
  94. {
  95. $query = $this->table->find('all');
  96. $results = $query->all();
  97. $expected = $results->toArray();
  98. $query2 = $this->table->find('all');
  99. $results2 = $query2->all();
  100. $serialized = serialize($results2);
  101. $outcome = unserialize($serialized);
  102. $this->assertEquals($expected, $outcome->toArray());
  103. }
  104. /**
  105. * Test iteration after serialization
  106. *
  107. * @return void
  108. */
  109. public function testIteratorAfterSerializationNoHydration()
  110. {
  111. $query = $this->table->find('all')->enableHydration(false);
  112. $results = unserialize(serialize($query->all()));
  113. // Use a loop to test Iterator implementation
  114. foreach ($results as $i => $row) {
  115. $this->assertEquals($this->fixtureData[$i], $row, "Row $i does not match");
  116. }
  117. }
  118. /**
  119. * Test iteration after serialization
  120. *
  121. * @return void
  122. */
  123. public function testIteratorAfterSerializationHydrated()
  124. {
  125. $query = $this->table->find('all');
  126. $results = unserialize(serialize($query->all()));
  127. // Use a loop to test Iterator implementation
  128. foreach ($results as $i => $row) {
  129. $expected = new Entity($this->fixtureData[$i]);
  130. $expected->isNew(false);
  131. $expected->setSource($this->table->getAlias());
  132. $expected->clean();
  133. $this->assertEquals($expected, $row, "Row $i does not match");
  134. }
  135. }
  136. /**
  137. * Test converting resultsets into json
  138. *
  139. * @return void
  140. */
  141. public function testJsonSerialize()
  142. {
  143. $query = $this->table->find('all');
  144. $results = $query->all();
  145. $expected = json_encode($this->fixtureData);
  146. $this->assertEquals($expected, json_encode($results));
  147. }
  148. /**
  149. * Test first() method with a statement backed result set.
  150. *
  151. * @return void
  152. */
  153. public function testFirst()
  154. {
  155. $query = $this->table->find('all');
  156. $results = $query->enableHydration(false)->all();
  157. $row = $results->first();
  158. $this->assertEquals($this->fixtureData[0], $row);
  159. $row = $results->first();
  160. $this->assertEquals($this->fixtureData[0], $row);
  161. }
  162. /**
  163. * Test first() method with a result set that has been unserialized
  164. *
  165. * @return void
  166. */
  167. public function testFirstAfterSerialize()
  168. {
  169. $query = $this->table->find('all');
  170. $results = $query->enableHydration(false)->all();
  171. $results = unserialize(serialize($results));
  172. $row = $results->first();
  173. $this->assertEquals($this->fixtureData[0], $row);
  174. $this->assertSame($row, $results->first());
  175. $this->assertSame($row, $results->first());
  176. }
  177. /**
  178. * Test the countable interface.
  179. *
  180. * @return void
  181. */
  182. public function testCount()
  183. {
  184. $query = $this->table->find('all');
  185. $results = $query->all();
  186. $this->assertCount(3, $results, 'Should be countable and 3');
  187. }
  188. /**
  189. * Test the countable interface after unserialize
  190. *
  191. * @return void
  192. */
  193. public function testCountAfterSerialize()
  194. {
  195. $query = $this->table->find('all');
  196. $results = $query->all();
  197. $results = unserialize(serialize($results));
  198. $this->assertCount(3, $results, 'Should be countable and 3');
  199. }
  200. /**
  201. * Integration test to show methods from CollectionTrait work
  202. *
  203. * @return void
  204. */
  205. public function testGroupBy()
  206. {
  207. $query = $this->table->find('all');
  208. $results = $query->all()->groupBy('author_id')->toArray();
  209. $options = [
  210. 'markNew' => false,
  211. 'markClean' => true,
  212. 'source' => $this->table->getAlias(),
  213. ];
  214. $expected = [
  215. 1 => [
  216. new Entity($this->fixtureData[0], $options),
  217. new Entity($this->fixtureData[2], $options),
  218. ],
  219. 3 => [
  220. new Entity($this->fixtureData[1], $options),
  221. ],
  222. ];
  223. $this->assertEquals($expected, $results);
  224. }
  225. /**
  226. * Tests __debugInfo
  227. *
  228. * @return void
  229. */
  230. public function testDebugInfo()
  231. {
  232. $query = $this->table->find('all');
  233. $results = $query->all();
  234. $expected = [
  235. 'items' => $results->toArray(),
  236. ];
  237. $this->assertSame($expected, $results->__debugInfo());
  238. }
  239. /**
  240. * Test that eagerLoader leaves empty associations unpopulated.
  241. *
  242. * @return void
  243. */
  244. public function testBelongsToEagerLoaderLeavesEmptyAssociation()
  245. {
  246. $comments = $this->getTableLocator()->get('Comments');
  247. $comments->belongsTo('Articles');
  248. // Clear the articles table so we can trigger an empty belongsTo
  249. $this->table->deleteAll([]);
  250. $comment = $comments->find()->where(['Comments.id' => 1])
  251. ->contain(['Articles'])
  252. ->enableHydration(false)
  253. ->first();
  254. $this->assertEquals(1, $comment['id']);
  255. $this->assertNotEmpty($comment['comment']);
  256. $this->assertNull($comment['article']);
  257. $comment = $comments->get(1, ['contain' => ['Articles']]);
  258. $this->assertNull($comment->article);
  259. $this->assertEquals(1, $comment->id);
  260. $this->assertNotEmpty($comment->comment);
  261. }
  262. /**
  263. * Test showing associated record is preserved when selecting only field with
  264. * null value if auto fields is disabled.
  265. *
  266. * @return void
  267. */
  268. public function testBelongsToEagerLoaderWithAutoFieldsFalse()
  269. {
  270. $authors = $this->getTableLocator()->get('Authors');
  271. $author = $authors->newEntity(['name' => null]);
  272. $authors->save($author);
  273. $articles = $this->getTableLocator()->get('Articles');
  274. $articles->belongsTo('Authors');
  275. $article = $articles->newEntity([
  276. 'author_id' => $author->id,
  277. 'title' => 'article with author with null name',
  278. ]);
  279. $articles->save($article);
  280. $result = $articles->find()
  281. ->select(['Articles.id', 'Articles.title', 'Authors.name'])
  282. ->contain(['Authors'])
  283. ->where(['Articles.id' => $article->id])
  284. ->enableAutoFields(false)
  285. ->enableHydration(false)
  286. ->first();
  287. $this->assertNotNull($result['author']);
  288. }
  289. /**
  290. * Test that eagerLoader leaves empty associations unpopulated.
  291. *
  292. * @return void
  293. */
  294. public function testHasOneEagerLoaderLeavesEmptyAssociation()
  295. {
  296. $this->table->hasOne('Comments');
  297. // Clear the comments table so we can trigger an empty hasOne.
  298. $comments = $this->getTableLocator()->get('Comments');
  299. $comments->deleteAll([]);
  300. $article = $this->table->get(1, ['contain' => ['Comments']]);
  301. $this->assertNull($article->comment);
  302. $this->assertEquals(1, $article->id);
  303. $this->assertNotEmpty($article->title);
  304. $article = $this->table->find()->where(['articles.id' => 1])
  305. ->contain(['Comments'])
  306. ->enableHydration(false)
  307. ->first();
  308. $this->assertNull($article['comment']);
  309. $this->assertEquals(1, $article['id']);
  310. $this->assertNotEmpty($article['title']);
  311. }
  312. /**
  313. * Test that fetching rows does not fail when no fields were selected
  314. * on the default alias.
  315. *
  316. * @return void
  317. */
  318. public function testFetchMissingDefaultAlias()
  319. {
  320. $comments = $this->getTableLocator()->get('Comments');
  321. $query = $comments->find()->select(['Other__field' => 'test']);
  322. $query->enableAutoFields(false);
  323. $row = ['Other__field' => 'test'];
  324. $statement = $this->getMockBuilder('Cake\Database\StatementInterface')->getMock();
  325. $statement->method('fetch')
  326. ->will($this->onConsecutiveCalls($row, $row));
  327. $statement->method('rowCount')
  328. ->will($this->returnValue(1));
  329. $result = new ResultSet($query, $statement);
  330. $result->valid();
  331. $this->assertNotEmpty($result->current());
  332. }
  333. /**
  334. * Test that associations have source() correctly set.
  335. *
  336. * @return void
  337. */
  338. public function testSourceOnContainAssociations()
  339. {
  340. $this->loadPlugins(['TestPlugin']);
  341. $comments = $this->getTableLocator()->get('TestPlugin.Comments');
  342. $comments->belongsTo('Authors', [
  343. 'className' => 'TestPlugin.Authors',
  344. 'foreignKey' => 'user_id',
  345. ]);
  346. $result = $comments->find()->contain(['Authors'])->first();
  347. $this->assertEquals('TestPlugin.Comments', $result->getSource());
  348. $this->assertEquals('TestPlugin.Authors', $result->author->getSource());
  349. $result = $comments->find()->matching('Authors', function ($q) {
  350. return $q->where(['Authors.id' => 1]);
  351. })->first();
  352. $this->assertEquals('TestPlugin.Comments', $result->getSource());
  353. $this->assertEquals('TestPlugin.Authors', $result->_matchingData['Authors']->getSource());
  354. $this->clearPlugins();
  355. }
  356. /**
  357. * Ensure that isEmpty() on a ResultSet doesn't result in loss
  358. * of records. This behavior is provided by CollectionTrait.
  359. *
  360. * @return void
  361. */
  362. public function testIsEmptyDoesNotConsumeData()
  363. {
  364. $table = $this->getTableLocator()->get('Comments');
  365. $query = $table->find()
  366. ->formatResults(function ($results) {
  367. return $results;
  368. });
  369. $res = $query->all();
  370. $res->isEmpty();
  371. $this->assertCount(6, $res->toArray());
  372. }
  373. /**
  374. * Test that ResultSet
  375. *
  376. * @return void
  377. */
  378. public function testCollectionMinAndMax()
  379. {
  380. $query = $this->table->find('all');
  381. $min = $query->min('id');
  382. $minExpected = $this->table->get(1);
  383. $max = $query->max('id');
  384. $maxExpected = $this->table->get(3);
  385. $this->assertEquals($minExpected, $min);
  386. $this->assertEquals($maxExpected, $max);
  387. }
  388. /**
  389. * Test that ResultSet
  390. *
  391. * @return void
  392. */
  393. public function testCollectionMinAndMaxWithAggregateField()
  394. {
  395. $query = $this->table->find();
  396. $query->select([
  397. 'counter' => 'COUNT(*)',
  398. ])->group('author_id');
  399. $min = $query->min('counter');
  400. $max = $query->max('counter');
  401. $this->assertTrue($max > $min);
  402. }
  403. }