ResultSetTest.php 12 KB

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