PageRenderTime 37ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/tests/TestCase/ORM/QueryTest.php

https://github.com/ceeram/cakephp
PHP | 2550 lines | 1870 code | 212 blank | 468 comment | 2 complexity | fe3ad3f09f068aa66cee0ca60c135cca MD5 | raw file
  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\Database\Expression\IdentifierExpression;
  17. use Cake\Database\Expression\OrderByExpression;
  18. use Cake\Database\Expression\QueryExpression;
  19. use Cake\Database\TypeMap;
  20. use Cake\Datasource\ConnectionManager;
  21. use Cake\ORM\Query;
  22. use Cake\ORM\ResultSet;
  23. use Cake\ORM\Table;
  24. use Cake\ORM\TableRegistry;
  25. use Cake\TestSuite\TestCase;
  26. /**
  27. * Tests Query class
  28. */
  29. class QueryTest extends TestCase
  30. {
  31. /**
  32. * Fixture to be used
  33. *
  34. * @var array
  35. */
  36. public $fixtures = ['core.articles', 'core.authors', 'core.tags',
  37. 'core.articles_tags', 'core.posts'];
  38. /**
  39. * setUp method
  40. *
  41. * @return void
  42. */
  43. public function setUp()
  44. {
  45. parent::setUp();
  46. $this->connection = ConnectionManager::get('test');
  47. $schema = [
  48. 'id' => ['type' => 'integer'],
  49. '_constraints' => [
  50. 'primary' => ['type' => 'primary', 'columns' => ['id']]
  51. ]
  52. ];
  53. $schema1 = [
  54. 'id' => ['type' => 'integer'],
  55. 'name' => ['type' => 'string'],
  56. 'phone' => ['type' => 'string'],
  57. '_constraints' => [
  58. 'primary' => ['type' => 'primary', 'columns' => ['id']]
  59. ]
  60. ];
  61. $schema2 = [
  62. 'id' => ['type' => 'integer'],
  63. 'total' => ['type' => 'string'],
  64. 'placed' => ['type' => 'datetime'],
  65. '_constraints' => [
  66. 'primary' => ['type' => 'primary', 'columns' => ['id']]
  67. ]
  68. ];
  69. $this->table = $table = TableRegistry::get('foo', ['schema' => $schema]);
  70. $clients = TableRegistry::get('clients', ['schema' => $schema1]);
  71. $orders = TableRegistry::get('orders', ['schema' => $schema2]);
  72. $companies = TableRegistry::get('companies', ['schema' => $schema, 'table' => 'organizations']);
  73. $orderTypes = TableRegistry::get('orderTypes', ['schema' => $schema]);
  74. $stuff = TableRegistry::get('stuff', ['schema' => $schema, 'table' => 'things']);
  75. $stuffTypes = TableRegistry::get('stuffTypes', ['schema' => $schema]);
  76. $categories = TableRegistry::get('categories', ['schema' => $schema]);
  77. $table->belongsTo('clients');
  78. $clients->hasOne('orders');
  79. $clients->belongsTo('companies');
  80. $orders->belongsTo('orderTypes');
  81. $orders->hasOne('stuff');
  82. $stuff->belongsTo('stuffTypes');
  83. $companies->belongsTo('categories');
  84. $this->fooTypeMap = new TypeMap(['foo.id' => 'integer', 'id' => 'integer']);
  85. }
  86. /**
  87. * tearDown method
  88. *
  89. * @return void
  90. */
  91. public function tearDown()
  92. {
  93. parent::tearDown();
  94. TableRegistry::clear();
  95. }
  96. /**
  97. * Provides strategies for associations that can be joined
  98. *
  99. * @return void
  100. */
  101. public function internalStategiesProvider()
  102. {
  103. return [['join'], ['select'], ['subquery']];
  104. }
  105. /**
  106. * Tests that results are grouped correctly when using contain()
  107. * and results are not hydrated
  108. *
  109. * @dataProvider internalStategiesProvider
  110. * @return void
  111. */
  112. public function testContainResultFetchingOneLevel($strategy)
  113. {
  114. $table = TableRegistry::get('articles', ['table' => 'articles']);
  115. $table->belongsTo('authors', ['strategy' => $strategy]);
  116. $query = new Query($this->connection, $table);
  117. $results = $query->select()
  118. ->contain('authors')
  119. ->hydrate(false)
  120. ->order(['articles.id' => 'asc'])
  121. ->toArray();
  122. $expected = [
  123. [
  124. 'id' => 1,
  125. 'title' => 'First Article',
  126. 'body' => 'First Article Body',
  127. 'author_id' => 1,
  128. 'published' => 'Y',
  129. 'author' => [
  130. 'id' => 1,
  131. 'name' => 'mariano'
  132. ]
  133. ],
  134. [
  135. 'id' => 2,
  136. 'title' => 'Second Article',
  137. 'body' => 'Second Article Body',
  138. 'author_id' => 3,
  139. 'published' => 'Y',
  140. 'author' => [
  141. 'id' => 3,
  142. 'name' => 'larry'
  143. ]
  144. ],
  145. [
  146. 'id' => 3,
  147. 'title' => 'Third Article',
  148. 'body' => 'Third Article Body',
  149. 'author_id' => 1,
  150. 'published' => 'Y',
  151. 'author' => [
  152. 'id' => 1,
  153. 'name' => 'mariano'
  154. ]
  155. ],
  156. ];
  157. $this->assertEquals($expected, $results);
  158. }
  159. /**
  160. * Data provider for the two types of strategies HasMany implements
  161. *
  162. * @return void
  163. */
  164. public function strategiesProvider()
  165. {
  166. return [['subquery'], ['select']];
  167. }
  168. /**
  169. * Tests that HasMany associations are correctly eager loaded and results
  170. * correctly nested when no hydration is used
  171. * Also that the query object passes the correct parent model keys to the
  172. * association objects in order to perform eager loading with select strategy
  173. *
  174. * @dataProvider strategiesProvider
  175. * @return void
  176. */
  177. public function testHasManyEagerLoadingNoHydration($strategy)
  178. {
  179. $table = TableRegistry::get('authors');
  180. TableRegistry::get('articles');
  181. $table->hasMany('articles', [
  182. 'propertyName' => 'articles',
  183. 'strategy' => $strategy,
  184. 'sort' => ['articles.id' => 'asc']
  185. ]);
  186. $query = new Query($this->connection, $table);
  187. $results = $query->select()
  188. ->contain('articles')
  189. ->hydrate(false)
  190. ->toArray();
  191. $expected = [
  192. [
  193. 'id' => 1,
  194. 'name' => 'mariano',
  195. 'articles' => [
  196. [
  197. 'id' => 1,
  198. 'title' => 'First Article',
  199. 'body' => 'First Article Body',
  200. 'author_id' => 1,
  201. 'published' => 'Y',
  202. ],
  203. [
  204. 'id' => 3,
  205. 'title' => 'Third Article',
  206. 'body' => 'Third Article Body',
  207. 'author_id' => 1,
  208. 'published' => 'Y',
  209. ],
  210. ]
  211. ],
  212. [
  213. 'id' => 2,
  214. 'name' => 'nate',
  215. 'articles' => [],
  216. ],
  217. [
  218. 'id' => 3,
  219. 'name' => 'larry',
  220. 'articles' => [
  221. [
  222. 'id' => 2,
  223. 'title' => 'Second Article',
  224. 'body' => 'Second Article Body',
  225. 'author_id' => 3,
  226. 'published' => 'Y'
  227. ]
  228. ]
  229. ],
  230. [
  231. 'id' => 4,
  232. 'name' => 'garrett',
  233. 'articles' => [],
  234. ]
  235. ];
  236. $this->assertEquals($expected, $results);
  237. $results = $query->repository($table)
  238. ->select()
  239. ->contain(['articles' => ['conditions' => ['articles.id' => 2]]])
  240. ->hydrate(false)
  241. ->toArray();
  242. $expected[0]['articles'] = [];
  243. $this->assertEquals($expected, $results);
  244. $this->assertEquals($table->association('articles')->strategy(), $strategy);
  245. }
  246. /**
  247. * Tests that it is possible to count results containing hasMany associations
  248. * both hydrating and not hydrating the results.
  249. *
  250. * @dataProvider strategiesProvider
  251. * @return void
  252. */
  253. public function testHasManyEagerLoadingCount($strategy)
  254. {
  255. $table = TableRegistry::get('authors');
  256. TableRegistry::get('articles');
  257. $table->hasMany('articles', [
  258. 'property' => 'articles',
  259. 'strategy' => $strategy,
  260. 'sort' => ['articles.id' => 'asc']
  261. ]);
  262. $query = new Query($this->connection, $table);
  263. $query = $query->select()
  264. ->contain('articles');
  265. $expected = 4;
  266. $results = $query->hydrate(false)
  267. ->count();
  268. $this->assertEquals($expected, $results);
  269. $results = $query->hydrate(true)
  270. ->count();
  271. $this->assertEquals($expected, $results);
  272. }
  273. /**
  274. * Tests that it is possible to set fields & order in a hasMany result set
  275. *
  276. * @dataProvider strategiesProvider
  277. * @return void
  278. */
  279. public function testHasManyEagerLoadingFieldsAndOrderNoHydration($strategy)
  280. {
  281. $table = TableRegistry::get('authors');
  282. TableRegistry::get('articles');
  283. $table->hasMany('articles', ['propertyName' => 'articles'] + compact('strategy'));
  284. $query = new Query($this->connection, $table);
  285. $results = $query->select()
  286. ->contain([
  287. 'articles' => [
  288. 'fields' => ['title', 'author_id'],
  289. 'sort' => ['articles.id' => 'DESC']
  290. ]
  291. ])
  292. ->hydrate(false)
  293. ->toArray();
  294. $expected = [
  295. [
  296. 'id' => 1,
  297. 'name' => 'mariano',
  298. 'articles' => [
  299. ['title' => 'Third Article', 'author_id' => 1],
  300. ['title' => 'First Article', 'author_id' => 1],
  301. ]
  302. ],
  303. [
  304. 'id' => 2,
  305. 'name' => 'nate',
  306. 'articles' => [],
  307. ],
  308. [
  309. 'id' => 3,
  310. 'name' => 'larry',
  311. 'articles' => [
  312. ['title' => 'Second Article', 'author_id' => 3],
  313. ]
  314. ],
  315. [
  316. 'id' => 4,
  317. 'name' => 'garrett',
  318. 'articles' => [],
  319. ],
  320. ];
  321. $this->assertEquals($expected, $results);
  322. }
  323. /**
  324. * Tests that deep associations can be eagerly loaded
  325. *
  326. * @dataProvider strategiesProvider
  327. * @return void
  328. */
  329. public function testHasManyEagerLoadingDeep($strategy)
  330. {
  331. $table = TableRegistry::get('authors');
  332. $article = TableRegistry::get('articles');
  333. $table->hasMany('articles', [
  334. 'propertyName' => 'articles',
  335. 'strategy' => $strategy,
  336. 'sort' => ['articles.id' => 'asc']
  337. ]);
  338. $article->belongsTo('authors');
  339. $query = new Query($this->connection, $table);
  340. $results = $query->select()
  341. ->contain(['articles' => ['authors']])
  342. ->hydrate(false)
  343. ->toArray();
  344. $expected = [
  345. [
  346. 'id' => 1,
  347. 'name' => 'mariano',
  348. 'articles' => [
  349. [
  350. 'id' => 1,
  351. 'title' => 'First Article',
  352. 'author_id' => 1,
  353. 'body' => 'First Article Body',
  354. 'published' => 'Y',
  355. 'author' => ['id' => 1, 'name' => 'mariano']
  356. ],
  357. [
  358. 'id' => 3,
  359. 'title' => 'Third Article',
  360. 'author_id' => 1,
  361. 'body' => 'Third Article Body',
  362. 'published' => 'Y',
  363. 'author' => ['id' => 1, 'name' => 'mariano']
  364. ],
  365. ]
  366. ],
  367. [
  368. 'id' => 2,
  369. 'name' => 'nate',
  370. 'articles' => [],
  371. ],
  372. [
  373. 'id' => 3,
  374. 'name' => 'larry',
  375. 'articles' => [
  376. [
  377. 'id' => 2,
  378. 'title' => 'Second Article',
  379. 'author_id' => 3,
  380. 'body' => 'Second Article Body',
  381. 'published' => 'Y',
  382. 'author' => ['id' => 3, 'name' => 'larry']
  383. ],
  384. ]
  385. ],
  386. [
  387. 'id' => 4,
  388. 'name' => 'garrett',
  389. 'articles' => [],
  390. ]
  391. ];
  392. $this->assertEquals($expected, $results);
  393. }
  394. /**
  395. * Tests that hasMany associations can be loaded even when related to a secondary
  396. * model in the query
  397. *
  398. * @dataProvider strategiesProvider
  399. * @return void
  400. */
  401. public function testHasManyEagerLoadingFromSecondaryTable($strategy)
  402. {
  403. $author = TableRegistry::get('authors');
  404. $article = TableRegistry::get('articles');
  405. $post = TableRegistry::get('posts');
  406. $author->hasMany('posts', [
  407. 'sort' => ['posts.id' => 'ASC'],
  408. 'strategy' => $strategy
  409. ]);
  410. $article->belongsTo('authors');
  411. $query = new Query($this->connection, $article);
  412. $results = $query->select()
  413. ->contain(['authors' => ['posts']])
  414. ->order(['articles.id' => 'ASC'])
  415. ->hydrate(false)
  416. ->toArray();
  417. $expected = [
  418. [
  419. 'id' => 1,
  420. 'title' => 'First Article',
  421. 'body' => 'First Article Body',
  422. 'author_id' => 1,
  423. 'published' => 'Y',
  424. 'author' => [
  425. 'id' => 1,
  426. 'name' => 'mariano',
  427. 'posts' => [
  428. [
  429. 'id' => '1',
  430. 'title' => 'First Post',
  431. 'body' => 'First Post Body',
  432. 'author_id' => 1,
  433. 'published' => 'Y',
  434. ],
  435. [
  436. 'id' => '3',
  437. 'title' => 'Third Post',
  438. 'body' => 'Third Post Body',
  439. 'author_id' => 1,
  440. 'published' => 'Y',
  441. ],
  442. ]
  443. ]
  444. ],
  445. [
  446. 'id' => 2,
  447. 'title' => 'Second Article',
  448. 'body' => 'Second Article Body',
  449. 'author_id' => 3,
  450. 'published' => 'Y',
  451. 'author' => [
  452. 'id' => 3,
  453. 'name' => 'larry',
  454. 'posts' => [
  455. [
  456. 'id' => 2,
  457. 'title' => 'Second Post',
  458. 'body' => 'Second Post Body',
  459. 'author_id' => 3,
  460. 'published' => 'Y',
  461. ]
  462. ]
  463. ]
  464. ],
  465. [
  466. 'id' => 3,
  467. 'title' => 'Third Article',
  468. 'body' => 'Third Article Body',
  469. 'author_id' => 1,
  470. 'published' => 'Y',
  471. 'author' => [
  472. 'id' => 1,
  473. 'name' => 'mariano',
  474. 'posts' => [
  475. [
  476. 'id' => '1',
  477. 'title' => 'First Post',
  478. 'body' => 'First Post Body',
  479. 'author_id' => 1,
  480. 'published' => 'Y',
  481. ],
  482. [
  483. 'id' => '3',
  484. 'title' => 'Third Post',
  485. 'body' => 'Third Post Body',
  486. 'author_id' => 1,
  487. 'published' => 'Y',
  488. ],
  489. ]
  490. ]
  491. ],
  492. ];
  493. $this->assertEquals($expected, $results);
  494. }
  495. /**
  496. * Tests that BelongsToMany associations are correctly eager loaded.
  497. * Also that the query object passes the correct parent model keys to the
  498. * association objects in order to perform eager loading with select strategy
  499. *
  500. * @dataProvider strategiesProvider
  501. * @return void
  502. */
  503. public function testBelongsToManyEagerLoadingNoHydration($strategy)
  504. {
  505. $table = TableRegistry::get('Articles');
  506. TableRegistry::get('Tags');
  507. TableRegistry::get('ArticlesTags', [
  508. 'table' => 'articles_tags'
  509. ]);
  510. $table->belongsToMany('Tags', ['strategy' => $strategy]);
  511. $query = new Query($this->connection, $table);
  512. $results = $query->select()->contain('Tags')->hydrate(false)->toArray();
  513. $expected = [
  514. [
  515. 'id' => 1,
  516. 'author_id' => 1,
  517. 'title' => 'First Article',
  518. 'body' => 'First Article Body',
  519. 'published' => 'Y',
  520. 'tags' => [
  521. [
  522. 'id' => 1,
  523. 'name' => 'tag1',
  524. '_joinData' => ['article_id' => 1, 'tag_id' => 1]
  525. ],
  526. [
  527. 'id' => 2,
  528. 'name' => 'tag2',
  529. '_joinData' => ['article_id' => 1, 'tag_id' => 2]
  530. ]
  531. ]
  532. ],
  533. [
  534. 'id' => 2,
  535. 'title' => 'Second Article',
  536. 'body' => 'Second Article Body',
  537. 'author_id' => 3,
  538. 'published' => 'Y',
  539. 'tags' => [
  540. [
  541. 'id' => 1,
  542. 'name' => 'tag1',
  543. '_joinData' => ['article_id' => 2, 'tag_id' => 1]
  544. ],
  545. [
  546. 'id' => 3,
  547. 'name' => 'tag3',
  548. '_joinData' => ['article_id' => 2, 'tag_id' => 3]
  549. ]
  550. ]
  551. ],
  552. [
  553. 'id' => 3,
  554. 'title' => 'Third Article',
  555. 'body' => 'Third Article Body',
  556. 'author_id' => 1,
  557. 'published' => 'Y',
  558. 'tags' => [],
  559. ],
  560. ];
  561. $this->assertEquals($expected, $results);
  562. $results = $query->select()
  563. ->contain(['Tags' => ['conditions' => ['Tags.id' => 3]]])
  564. ->hydrate(false)
  565. ->toArray();
  566. $expected = [
  567. [
  568. 'id' => 1,
  569. 'author_id' => 1,
  570. 'title' => 'First Article',
  571. 'body' => 'First Article Body',
  572. 'published' => 'Y',
  573. 'tags' => [],
  574. ],
  575. [
  576. 'id' => 2,
  577. 'title' => 'Second Article',
  578. 'body' => 'Second Article Body',
  579. 'author_id' => 3,
  580. 'published' => 'Y',
  581. 'tags' => [
  582. [
  583. 'id' => 3,
  584. 'name' => 'tag3',
  585. '_joinData' => ['article_id' => 2, 'tag_id' => 3]
  586. ]
  587. ]
  588. ],
  589. [
  590. 'id' => 3,
  591. 'title' => 'Third Article',
  592. 'body' => 'Third Article Body',
  593. 'author_id' => 1,
  594. 'published' => 'Y',
  595. 'tags' => [],
  596. ],
  597. ];
  598. $this->assertEquals($expected, $results);
  599. $this->assertEquals($table->association('Tags')->strategy(), $strategy);
  600. }
  601. /**
  602. * Tests that tables results can be filtered by the result of a HasMany
  603. *
  604. * @return void
  605. */
  606. public function testFilteringByHasManyNoHydration()
  607. {
  608. $query = new Query($this->connection, $this->table);
  609. $table = TableRegistry::get('authors');
  610. TableRegistry::get('articles');
  611. $table->hasMany('articles');
  612. $results = $query->repository($table)
  613. ->select()
  614. ->hydrate(false)
  615. ->matching('articles', function ($q) {
  616. return $q->where(['articles.id' => 2]);
  617. })
  618. ->toArray();
  619. $expected = [
  620. [
  621. 'id' => 3,
  622. 'name' => 'larry',
  623. '_matchingData' => [
  624. 'articles' => [
  625. 'id' => 2,
  626. 'title' => 'Second Article',
  627. 'body' => 'Second Article Body',
  628. 'author_id' => 3,
  629. 'published' => 'Y',
  630. ]
  631. ]
  632. ]
  633. ];
  634. $this->assertEquals($expected, $results);
  635. }
  636. /**
  637. * Tests that BelongsToMany associations are correctly eager loaded.
  638. * Also that the query object passes the correct parent model keys to the
  639. * association objects in order to perform eager loading with select strategy
  640. *
  641. * @return void
  642. */
  643. public function testFilteringByBelongsToManyNoHydration()
  644. {
  645. $query = new Query($this->connection, $this->table);
  646. $table = TableRegistry::get('Articles');
  647. TableRegistry::get('Tags');
  648. TableRegistry::get('ArticlesTags', [
  649. 'table' => 'articles_tags'
  650. ]);
  651. $table->belongsToMany('Tags');
  652. $results = $query->repository($table)->select()
  653. ->matching('Tags', function ($q) {
  654. return $q->where(['Tags.id' => 3]);
  655. })
  656. ->hydrate(false)
  657. ->toArray();
  658. $expected = [
  659. [
  660. 'id' => 2,
  661. 'author_id' => 3,
  662. 'title' => 'Second Article',
  663. 'body' => 'Second Article Body',
  664. 'published' => 'Y',
  665. '_matchingData' => [
  666. 'Tags' => [
  667. 'id' => 3,
  668. 'name' => 'tag3',
  669. ],
  670. 'ArticlesTags' => ['article_id' => 2, 'tag_id' => 3]
  671. ]
  672. ]
  673. ];
  674. $this->assertEquals($expected, $results);
  675. $query = new Query($this->connection, $table);
  676. $results = $query->select()
  677. ->matching('Tags', function ($q) {
  678. return $q->where(['Tags.name' => 'tag2']);
  679. })
  680. ->hydrate(false)
  681. ->toArray();
  682. $expected = [
  683. [
  684. 'id' => 1,
  685. 'title' => 'First Article',
  686. 'body' => 'First Article Body',
  687. 'author_id' => 1,
  688. 'published' => 'Y',
  689. '_matchingData' => [
  690. 'Tags' => [
  691. 'id' => 2,
  692. 'name' => 'tag2',
  693. ],
  694. 'ArticlesTags' => ['article_id' => 1, 'tag_id' => 2]
  695. ]
  696. ]
  697. ];
  698. $this->assertEquals($expected, $results);
  699. }
  700. /**
  701. * Tests that it is possible to filter by deep associations
  702. *
  703. * @return void
  704. */
  705. public function testMatchingDotNotation()
  706. {
  707. $query = new Query($this->connection, $this->table);
  708. $table = TableRegistry::get('authors');
  709. TableRegistry::get('articles');
  710. $table->hasMany('articles');
  711. TableRegistry::get('articles')->belongsToMany('tags');
  712. $results = $query->repository($table)
  713. ->select()
  714. ->hydrate(false)
  715. ->matching('articles.tags', function ($q) {
  716. return $q->where(['tags.id' => 2]);
  717. })
  718. ->toArray();
  719. $expected = [
  720. [
  721. 'id' => 1,
  722. 'name' => 'mariano',
  723. '_matchingData' => [
  724. 'tags' => [
  725. 'id' => 2,
  726. 'name' => 'tag2',
  727. ],
  728. 'articles' => [
  729. 'id' => 1,
  730. 'author_id' => 1,
  731. 'title' => 'First Article',
  732. 'body' => 'First Article Body',
  733. 'published' => 'Y'
  734. ],
  735. 'ArticlesTags' => [
  736. 'article_id' => 1,
  737. 'tag_id' => 2
  738. ]
  739. ]
  740. ]
  741. ];
  742. $this->assertEquals($expected, $results);
  743. }
  744. /**
  745. * Test setResult()
  746. *
  747. * @return void
  748. */
  749. public function testSetResult()
  750. {
  751. $query = new Query($this->connection, $this->table);
  752. $stmt = $this->getMock('Cake\Database\StatementInterface');
  753. $results = new ResultSet($query, $stmt);
  754. $query->setResult($results);
  755. $this->assertSame($results, $query->all());
  756. }
  757. /**
  758. * Tests that applying array options to a query will convert them
  759. * to equivalent function calls with the correspondent array values
  760. *
  761. * @return void
  762. */
  763. public function testApplyOptions()
  764. {
  765. $options = [
  766. 'fields' => ['field_a', 'field_b'],
  767. 'conditions' => ['field_a' => 1, 'field_b' => 'something'],
  768. 'limit' => 1,
  769. 'order' => ['a' => 'ASC'],
  770. 'offset' => 5,
  771. 'group' => ['field_a'],
  772. 'having' => ['field_a >' => 100],
  773. 'contain' => ['table_a' => ['table_b']],
  774. 'join' => ['table_a' => ['conditions' => ['a > b']]]
  775. ];
  776. $query = new Query($this->connection, $this->table);
  777. $query->applyOptions($options);
  778. $this->assertEquals(['field_a', 'field_b'], $query->clause('select'));
  779. $expected = new QueryExpression($options['conditions'], $this->fooTypeMap);
  780. $result = $query->clause('where');
  781. $this->assertEquals($expected, $result);
  782. $this->assertEquals(1, $query->clause('limit'));
  783. $expected = new QueryExpression(['a > b']);
  784. $expected->typeMap($this->fooTypeMap);
  785. $result = $query->clause('join');
  786. $this->assertEquals([
  787. 'table_a' => ['alias' => 'table_a', 'type' => 'INNER', 'conditions' => $expected]
  788. ], $result);
  789. $expected = new OrderByExpression(['a' => 'ASC']);
  790. $this->assertEquals($expected, $query->clause('order'));
  791. $this->assertEquals(5, $query->clause('offset'));
  792. $this->assertEquals(['field_a'], $query->clause('group'));
  793. $expected = new QueryExpression($options['having']);
  794. $expected->typeMap($this->fooTypeMap);
  795. $this->assertEquals($expected, $query->clause('having'));
  796. $expected = ['table_a' => ['table_b' => []]];
  797. $this->assertEquals($expected, $query->contain());
  798. }
  799. /**
  800. * Test that page is applied after limit.
  801. *
  802. * @return void
  803. */
  804. public function testApplyOptionsPageIsLast()
  805. {
  806. $query = new Query($this->connection, $this->table);
  807. $opts = [
  808. 'page' => 3,
  809. 'limit' => 5
  810. ];
  811. $query->applyOptions($opts);
  812. $this->assertEquals(5, $query->clause('limit'));
  813. $this->assertEquals(10, $query->clause('offset'));
  814. }
  815. /**
  816. * ApplyOptions should ignore null values.
  817. *
  818. * @return void
  819. */
  820. public function testApplyOptionsIgnoreNull()
  821. {
  822. $options = [
  823. 'fields' => null,
  824. ];
  825. $query = new Query($this->connection, $this->table);
  826. $query->applyOptions($options);
  827. $this->assertEquals([], $query->clause('select'));
  828. }
  829. /**
  830. * Tests getOptions() method
  831. *
  832. * @return void
  833. */
  834. public function testGetOptions()
  835. {
  836. $options = ['doABarrelRoll' => true, 'fields' => ['id', 'name']];
  837. $query = new Query($this->connection, $this->table);
  838. $query->applyOptions($options);
  839. $expected = ['doABarrelRoll' => true];
  840. $this->assertEquals($expected, $query->getOptions());
  841. $expected = ['doABarrelRoll' => false, 'doAwesome' => true];
  842. $query->applyOptions($expected);
  843. $this->assertEquals($expected, $query->getOptions());
  844. }
  845. /**
  846. * Tests registering mappers with mapReduce()
  847. *
  848. * @return void
  849. */
  850. public function testMapReduceOnlyMapper()
  851. {
  852. $mapper1 = function () {
  853. };
  854. $mapper2 = function () {
  855. };
  856. $query = new Query($this->connection, $this->table);
  857. $this->assertSame($query, $query->mapReduce($mapper1));
  858. $this->assertEquals(
  859. [['mapper' => $mapper1, 'reducer' => null]],
  860. $query->mapReduce()
  861. );
  862. $this->assertEquals($query, $query->mapReduce($mapper2));
  863. $result = $query->mapReduce();
  864. $this->assertSame(
  865. [
  866. ['mapper' => $mapper1, 'reducer' => null],
  867. ['mapper' => $mapper2, 'reducer' => null]
  868. ],
  869. $result
  870. );
  871. }
  872. /**
  873. * Tests registering mappers and reducers with mapReduce()
  874. *
  875. * @return void
  876. */
  877. public function testMapReduceBothMethods()
  878. {
  879. $mapper1 = function () {
  880. };
  881. $mapper2 = function () {
  882. };
  883. $reducer1 = function () {
  884. };
  885. $reducer2 = function () {
  886. };
  887. $query = new Query($this->connection, $this->table);
  888. $this->assertSame($query, $query->mapReduce($mapper1, $reducer1));
  889. $this->assertEquals(
  890. [['mapper' => $mapper1, 'reducer' => $reducer1]],
  891. $query->mapReduce()
  892. );
  893. $this->assertSame($query, $query->mapReduce($mapper2, $reducer2));
  894. $this->assertEquals(
  895. [
  896. ['mapper' => $mapper1, 'reducer' => $reducer1],
  897. ['mapper' => $mapper2, 'reducer' => $reducer2]
  898. ],
  899. $query->mapReduce()
  900. );
  901. }
  902. /**
  903. * Tests that it is possible to overwrite previous map reducers
  904. *
  905. * @return void
  906. */
  907. public function testOverwriteMapReduce()
  908. {
  909. $mapper1 = function () {
  910. };
  911. $mapper2 = function () {
  912. };
  913. $reducer1 = function () {
  914. };
  915. $reducer2 = function () {
  916. };
  917. $query = new Query($this->connection, $this->table);
  918. $this->assertEquals($query, $query->mapReduce($mapper1, $reducer1));
  919. $this->assertEquals(
  920. [['mapper' => $mapper1, 'reducer' => $reducer1]],
  921. $query->mapReduce()
  922. );
  923. $this->assertEquals($query, $query->mapReduce($mapper2, $reducer2, true));
  924. $this->assertEquals(
  925. [['mapper' => $mapper2, 'reducer' => $reducer2]],
  926. $query->mapReduce()
  927. );
  928. }
  929. /**
  930. * Tests that multiple map reducers can be stacked
  931. *
  932. * @return void
  933. */
  934. public function testResultsAreWrappedInMapReduce()
  935. {
  936. $params = [$this->connection, $this->table];
  937. $query = $this->getMock('\Cake\ORM\Query', ['execute'], $params);
  938. $statement = $this->getMock(
  939. '\Database\StatementInterface',
  940. ['fetch', 'closeCursor', 'rowCount']
  941. );
  942. $statement->expects($this->exactly(2))
  943. ->method('fetch')
  944. ->will($this->onConsecutiveCalls(['a' => 1], ['a' => 2]));
  945. $statement->expects($this->once())
  946. ->method('rowCount')
  947. ->will($this->returnValue(2));
  948. $query->expects($this->once())
  949. ->method('execute')
  950. ->will($this->returnValue($statement));
  951. $query->mapReduce(function ($v, $k, $mr) {
  952. $mr->emit($v['a']);
  953. });
  954. $query->mapReduce(
  955. function ($v, $k, $mr) {
  956. $mr->emitIntermediate($v, $k);
  957. },
  958. function ($v, $k, $mr) {
  959. $mr->emit($v[0] + 1);
  960. }
  961. );
  962. $this->assertEquals([2, 3], iterator_to_array($query->all()));
  963. }
  964. /**
  965. * Tests first() method when the query has not been executed before
  966. *
  967. * @return void
  968. */
  969. public function testFirstDirtyQuery()
  970. {
  971. $table = TableRegistry::get('articles', ['table' => 'articles']);
  972. $query = new Query($this->connection, $table);
  973. $result = $query->select(['id'])->hydrate(false)->first();
  974. $this->assertEquals(['id' => 1], $result);
  975. $this->assertEquals(1, $query->clause('limit'));
  976. $result = $query->select(['id'])->first();
  977. $this->assertEquals(['id' => 1], $result);
  978. }
  979. /**
  980. * Tests that first can be called again on an already executed query
  981. *
  982. * @return void
  983. */
  984. public function testFirstCleanQuery()
  985. {
  986. $table = TableRegistry::get('articles', ['table' => 'articles']);
  987. $query = new Query($this->connection, $table);
  988. $query->select(['id'])->toArray();
  989. $first = $query->hydrate(false)->first();
  990. $this->assertEquals(['id' => 1], $first);
  991. $this->assertEquals(1, $query->clause('limit'));
  992. }
  993. /**
  994. * Tests that first() will not execute the same query twice
  995. *
  996. * @return void
  997. */
  998. public function testFirstSameResult()
  999. {
  1000. $table = TableRegistry::get('articles', ['table' => 'articles']);
  1001. $query = new Query($this->connection, $table);
  1002. $query->select(['id'])->toArray();
  1003. $first = $query->hydrate(false)->first();
  1004. $resultSet = $query->all();
  1005. $this->assertEquals(['id' => 1], $first);
  1006. $this->assertSame($resultSet, $query->all());
  1007. }
  1008. /**
  1009. * Tests that first can be called against a query with a mapReduce
  1010. *
  1011. * @return void
  1012. */
  1013. public function testFirstMapReduce()
  1014. {
  1015. $map = function ($row, $key, $mapReduce) {
  1016. $mapReduce->emitIntermediate($row['id'], 'id');
  1017. };
  1018. $reduce = function ($values, $key, $mapReduce) {
  1019. $mapReduce->emit(array_sum($values));
  1020. };
  1021. $table = TableRegistry::get('articles', ['table' => 'articles']);
  1022. $query = new Query($this->connection, $table);
  1023. $query->select(['id'])
  1024. ->hydrate(false)
  1025. ->mapReduce($map, $reduce);
  1026. $first = $query->first();
  1027. $this->assertEquals(1, $first);
  1028. }
  1029. /**
  1030. * Tests that first can be called on an unbuffered query
  1031. *
  1032. * @return void
  1033. */
  1034. public function testFirstUnbuffered()
  1035. {
  1036. $table = TableRegistry::get('Articles');
  1037. $query = new Query($this->connection, $table);
  1038. $query->select(['id']);
  1039. $first = $query->hydrate(false)
  1040. ->bufferResults(false)->first();
  1041. $this->assertEquals(['id' => 1], $first);
  1042. }
  1043. /**
  1044. * Testing hydrating a result set into Entity objects
  1045. *
  1046. * @return void
  1047. */
  1048. public function testHydrateSimple()
  1049. {
  1050. $table = TableRegistry::get('articles', ['table' => 'articles']);
  1051. $query = new Query($this->connection, $table);
  1052. $results = $query->select()->toArray();
  1053. $this->assertCount(3, $results);
  1054. foreach ($results as $r) {
  1055. $this->assertInstanceOf('Cake\ORM\Entity', $r);
  1056. }
  1057. $first = $results[0];
  1058. $this->assertEquals(1, $first->id);
  1059. $this->assertEquals(1, $first->author_id);
  1060. $this->assertEquals('First Article', $first->title);
  1061. $this->assertEquals('First Article Body', $first->body);
  1062. $this->assertEquals('Y', $first->published);
  1063. }
  1064. /**
  1065. * Tests that has many results are also hydrated correctly
  1066. *
  1067. * @return void
  1068. */
  1069. public function testHydrateHasMany()
  1070. {
  1071. $table = TableRegistry::get('authors');
  1072. TableRegistry::get('articles');
  1073. $table->hasMany('articles', [
  1074. 'propertyName' => 'articles',
  1075. 'sort' => ['articles.id' => 'asc']
  1076. ]);
  1077. $query = new Query($this->connection, $table);
  1078. $results = $query->select()
  1079. ->contain('articles')
  1080. ->toArray();
  1081. $first = $results[0];
  1082. foreach ($first->articles as $r) {
  1083. $this->assertInstanceOf('Cake\ORM\Entity', $r);
  1084. }
  1085. $this->assertCount(2, $first->articles);
  1086. $expected = [
  1087. 'id' => 1,
  1088. 'title' => 'First Article',
  1089. 'body' => 'First Article Body',
  1090. 'author_id' => 1,
  1091. 'published' => 'Y',
  1092. ];
  1093. $this->assertEquals($expected, $first->articles[0]->toArray());
  1094. $expected = [
  1095. 'id' => 3,
  1096. 'title' => 'Third Article',
  1097. 'author_id' => 1,
  1098. 'body' => 'Third Article Body',
  1099. 'published' => 'Y',
  1100. ];
  1101. $this->assertEquals($expected, $first->articles[1]->toArray());
  1102. }
  1103. /**
  1104. * Tests that belongsToMany associations are also correctly hydrated
  1105. *
  1106. * @return void
  1107. */
  1108. public function testHydrateBelongsToMany()
  1109. {
  1110. $table = TableRegistry::get('Articles');
  1111. TableRegistry::get('Tags');
  1112. TableRegistry::get('ArticlesTags', [
  1113. 'table' => 'articles_tags'
  1114. ]);
  1115. $table->belongsToMany('Tags');
  1116. $query = new Query($this->connection, $table);
  1117. $results = $query
  1118. ->select()
  1119. ->contain('Tags')
  1120. ->toArray();
  1121. $first = $results[0];
  1122. foreach ($first->tags as $r) {
  1123. $this->assertInstanceOf('Cake\ORM\Entity', $r);
  1124. }
  1125. $this->assertCount(2, $first->tags);
  1126. $expected = [
  1127. 'id' => 1,
  1128. 'name' => 'tag1',
  1129. '_joinData' => ['article_id' => 1, 'tag_id' => 1]
  1130. ];
  1131. $this->assertEquals($expected, $first->tags[0]->toArray());
  1132. $expected = [
  1133. 'id' => 2,
  1134. 'name' => 'tag2',
  1135. '_joinData' => ['article_id' => 1, 'tag_id' => 2]
  1136. ];
  1137. $this->assertEquals($expected, $first->tags[1]->toArray());
  1138. }
  1139. /**
  1140. * Tests that belongsToMany associations are also correctly hydrated
  1141. *
  1142. * @return void
  1143. */
  1144. public function testFormatResultsBelongsToMany()
  1145. {
  1146. $table = TableRegistry::get('Articles');
  1147. TableRegistry::get('Tags');
  1148. $articlesTags = TableRegistry::get('ArticlesTags', [
  1149. 'table' => 'articles_tags'
  1150. ]);
  1151. $table->belongsToMany('Tags');
  1152. $articlesTags
  1153. ->eventManager()
  1154. ->attach(function ($event, $query) {
  1155. $query->formatResults(function ($results) {
  1156. return $results;
  1157. });
  1158. }, 'Model.beforeFind');
  1159. $query = new Query($this->connection, $table);
  1160. $results = $query
  1161. ->select()
  1162. ->contain('Tags')
  1163. ->toArray();
  1164. $first = $results[0];
  1165. foreach ($first->tags as $r) {
  1166. $this->assertInstanceOf('Cake\ORM\Entity', $r);
  1167. }
  1168. $this->assertCount(2, $first->tags);
  1169. $expected = [
  1170. 'id' => 1,
  1171. 'name' => 'tag1',
  1172. '_joinData' => ['article_id' => 1, 'tag_id' => 1]
  1173. ];
  1174. $this->assertEquals($expected, $first->tags[0]->toArray());
  1175. $expected = [
  1176. 'id' => 2,
  1177. 'name' => 'tag2',
  1178. '_joinData' => ['article_id' => 1, 'tag_id' => 2]
  1179. ];
  1180. $this->assertEquals($expected, $first->tags[1]->toArray());
  1181. }
  1182. /**
  1183. * Tests that belongsTo relations are correctly hydrated
  1184. *
  1185. * @dataProvider internalStategiesProvider
  1186. * @return void
  1187. */
  1188. public function testHydrateBelongsTo($strategy)
  1189. {
  1190. $table = TableRegistry::get('articles');
  1191. TableRegistry::get('authors');
  1192. $table->belongsTo('authors', ['strategy' => $strategy]);
  1193. $query = new Query($this->connection, $table);
  1194. $results = $query->select()
  1195. ->contain('authors')
  1196. ->order(['articles.id' => 'asc'])
  1197. ->toArray();
  1198. $this->assertCount(3, $results);
  1199. $first = $results[0];
  1200. $this->assertInstanceOf('Cake\ORM\Entity', $first->author);
  1201. $expected = ['id' => 1, 'name' => 'mariano'];
  1202. $this->assertEquals($expected, $first->author->toArray());
  1203. }
  1204. /**
  1205. * Tests that deeply nested associations are also hydrated correctly
  1206. *
  1207. * @dataProvider internalStategiesProvider
  1208. * @return void
  1209. */
  1210. public function testHydrateDeep($strategy)
  1211. {
  1212. $table = TableRegistry::get('authors');
  1213. $article = TableRegistry::get('articles');
  1214. $table->hasMany('articles', [
  1215. 'propertyName' => 'articles',
  1216. 'sort' => ['articles.id' => 'asc']
  1217. ]);
  1218. $article->belongsTo('authors', ['strategy' => $strategy]);
  1219. $query = new Query($this->connection, $table);
  1220. $results = $query->select()
  1221. ->contain(['articles' => ['authors']])
  1222. ->toArray();
  1223. $this->assertCount(4, $results);
  1224. $first = $results[0];
  1225. $this->assertInstanceOf('Cake\ORM\Entity', $first->articles[0]->author);
  1226. $expected = ['id' => 1, 'name' => 'mariano'];
  1227. $this->assertEquals($expected, $first->articles[0]->author->toArray());
  1228. $this->assertTrue(isset($results[3]->articles));
  1229. }
  1230. /**
  1231. * Tests that it is possible to use a custom entity class
  1232. *
  1233. * @return void
  1234. */
  1235. public function testHydrateCustomObject()
  1236. {
  1237. $class = $this->getMockClass('\Cake\ORM\Entity', ['fakeMethod']);
  1238. $table = TableRegistry::get('articles', [
  1239. 'table' => 'articles',
  1240. 'entityClass' => '\\' . $class
  1241. ]);
  1242. $query = new Query($this->connection, $table);
  1243. $results = $query->select()->toArray();
  1244. $this->assertCount(3, $results);
  1245. foreach ($results as $r) {
  1246. $this->assertInstanceOf($class, $r);
  1247. }
  1248. $first = $results[0];
  1249. $this->assertEquals(1, $first->id);
  1250. $this->assertEquals(1, $first->author_id);
  1251. $this->assertEquals('First Article', $first->title);
  1252. $this->assertEquals('First Article Body', $first->body);
  1253. $this->assertEquals('Y', $first->published);
  1254. }
  1255. /**
  1256. * Tests that has many results are also hydrated correctly
  1257. * when specified a custom entity class
  1258. *
  1259. * @return void
  1260. */
  1261. public function testHydrateHasManyCustomEntity()
  1262. {
  1263. $authorEntity = $this->getMockClass('\Cake\ORM\Entity', ['foo']);
  1264. $articleEntity = $this->getMockClass('\Cake\ORM\Entity', ['foo']);
  1265. $table = TableRegistry::get('authors', [
  1266. 'entityClass' => '\\' . $authorEntity
  1267. ]);
  1268. TableRegistry::get('articles', [
  1269. 'entityClass' => '\\' . $articleEntity
  1270. ]);
  1271. $table->hasMany('articles', [
  1272. 'propertyName' => 'articles',
  1273. 'sort' => ['articles.id' => 'asc']
  1274. ]);
  1275. $query = new Query($this->connection, $table);
  1276. $results = $query->select()
  1277. ->contain('articles')
  1278. ->toArray();
  1279. $first = $results[0];
  1280. $this->assertInstanceOf($authorEntity, $first);
  1281. foreach ($first->articles as $r) {
  1282. $this->assertInstanceOf($articleEntity, $r);
  1283. }
  1284. $this->assertCount(2, $first->articles);
  1285. $expected = [
  1286. 'id' => 1,
  1287. 'title' => 'First Article',
  1288. 'body' => 'First Article Body',
  1289. 'author_id' => 1,
  1290. 'published' => 'Y',
  1291. ];
  1292. $this->assertEquals($expected, $first->articles[0]->toArray());
  1293. }
  1294. /**
  1295. * Tests that belongsTo relations are correctly hydrated into a custom entity class
  1296. *
  1297. * @return void
  1298. */
  1299. public function testHydrateBelongsToCustomEntity()
  1300. {
  1301. $authorEntity = $this->getMockClass('\Cake\ORM\Entity', ['foo']);
  1302. $table = TableRegistry::get('articles');
  1303. TableRegistry::get('authors', [
  1304. 'entityClass' => '\\' . $authorEntity
  1305. ]);
  1306. $table->belongsTo('authors');
  1307. $query = new Query($this->connection, $table);
  1308. $results = $query->select()
  1309. ->contain('authors')
  1310. ->order(['articles.id' => 'asc'])
  1311. ->toArray();
  1312. $first = $results[0];
  1313. $this->assertInstanceOf($authorEntity, $first->author);
  1314. }
  1315. /**
  1316. * Test getting counts from queries.
  1317. *
  1318. * @return void
  1319. */
  1320. public function testCount()
  1321. {
  1322. $table = TableRegistry::get('articles');
  1323. $result = $table->find('all')->count();
  1324. $this->assertSame(3, $result);
  1325. $query = $table->find('all')
  1326. ->where(['id >' => 1])
  1327. ->limit(1);
  1328. $result = $query->count();
  1329. $this->assertSame(2, $result);
  1330. $result = $query->all();
  1331. $this->assertCount(1, $result);
  1332. $this->assertEquals(2, $result->first()->id);
  1333. }
  1334. /**
  1335. * Test getting counts from queries with contain.
  1336. *
  1337. * @return void
  1338. */
  1339. public function testCountWithContain()
  1340. {
  1341. $table = TableRegistry::get('Articles');
  1342. $table->belongsTo('Authors');
  1343. $result = $table->find('all')
  1344. ->contain([
  1345. 'Authors' => [
  1346. 'fields' => ['name']
  1347. ]
  1348. ])
  1349. ->count();
  1350. $this->assertSame(3, $result);
  1351. }
  1352. /**
  1353. * test count with a beforeFind.
  1354. *
  1355. * @return void
  1356. */
  1357. public function testCountBeforeFind()
  1358. {
  1359. $table = TableRegistry::get('Articles');
  1360. $table->hasMany('Comments');
  1361. $table->eventManager()
  1362. ->attach(function ($event, $query) {
  1363. $query
  1364. ->limit(1)
  1365. ->order(['Articles.title' => 'DESC']);
  1366. }, 'Model.beforeFind');
  1367. $query = $table->find();
  1368. $result = $query->count();
  1369. $this->assertSame(3, $result);
  1370. }
  1371. /**
  1372. * Test that count() returns correct results with group by.
  1373. *
  1374. * @return void
  1375. */
  1376. public function testCountWithGroup()
  1377. {
  1378. $table = TableRegistry::get('articles');
  1379. $query = $table->find('all');
  1380. $query->select(['author_id', 's' => $query->func()->sum('id')])
  1381. ->group(['author_id']);
  1382. $result = $query->count();
  1383. $this->assertEquals(2, $result);
  1384. }
  1385. /**
  1386. * Tests that it is possible to provide a callback for calculating the count
  1387. * of a query
  1388. *
  1389. * @return void
  1390. */
  1391. public function testCountWithCustomCounter()
  1392. {
  1393. $table = TableRegistry::get('articles');
  1394. $query = $table->find('all');
  1395. $query
  1396. ->select(['author_id', 's' => $query->func()->sum('id')])
  1397. ->where(['id >' => 2])
  1398. ->group(['author_id'])
  1399. ->counter(function ($q) use ($query) {
  1400. $this->assertNotSame($q, $query);
  1401. return $q->select([], true)->group([], true)->count();
  1402. });
  1403. $result = $query->count();
  1404. $this->assertEquals(1, $result);
  1405. }
  1406. /**
  1407. * Test update method.
  1408. *
  1409. * @return void
  1410. */
  1411. public function testUpdate()
  1412. {
  1413. $table = TableRegistry::get('articles');
  1414. $result = $table->query()
  1415. ->update()
  1416. ->set(['title' => 'First'])
  1417. ->execute();
  1418. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1419. $this->assertTrue($result->rowCount() > 0);
  1420. }
  1421. /**
  1422. * Test insert method.
  1423. *
  1424. * @return void
  1425. */
  1426. public function testInsert()
  1427. {
  1428. $table = TableRegistry::get('articles');
  1429. $result = $table->query()
  1430. ->insert(['title'])
  1431. ->values(['title' => 'First'])
  1432. ->values(['title' => 'Second'])
  1433. ->execute();
  1434. $result->closeCursor();
  1435. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1436. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  1437. if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
  1438. $this->assertEquals(2, $result->rowCount());
  1439. } else {
  1440. $this->assertEquals(-1, $result->rowCount());
  1441. }
  1442. }
  1443. /**
  1444. * Test delete method.
  1445. *
  1446. * @return void
  1447. */
  1448. public function testDelete()
  1449. {
  1450. $table = TableRegistry::get('articles');
  1451. $result = $table->query()
  1452. ->delete()
  1453. ->where(['id >=' => 1])
  1454. ->execute();
  1455. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1456. $this->assertTrue($result->rowCount() > 0);
  1457. }
  1458. /**
  1459. * Provides a list of collection methods that can be proxied
  1460. * from the query
  1461. *
  1462. * @return array
  1463. */
  1464. public function collectionMethodsProvider()
  1465. {
  1466. $identity = function ($a) {
  1467. return $a;
  1468. };
  1469. return [
  1470. ['filter', $identity],
  1471. ['reject', $identity],
  1472. ['every', $identity],
  1473. ['some', $identity],
  1474. ['contains', $identity],
  1475. ['map', $identity],
  1476. ['reduce', $identity],
  1477. ['extract', $identity],
  1478. ['max', $identity],
  1479. ['min', $identity],
  1480. ['sortBy', $identity],
  1481. ['groupBy', $identity],
  1482. ['countBy', $identity],
  1483. ['shuffle', $identity],
  1484. ['sample', $identity],
  1485. ['take', 1],
  1486. ['append', new \ArrayIterator],
  1487. ['compile', 1],
  1488. ];
  1489. }
  1490. /**
  1491. * Tests that query can proxy collection methods
  1492. *
  1493. * @dataProvider collectionMethodsProvider
  1494. * @return void
  1495. */
  1496. public function testCollectionProxy($method, $arg)
  1497. {
  1498. $query = $this->getMock(
  1499. '\Cake\ORM\Query',
  1500. ['all'],
  1501. [$this->connection, $this->table]
  1502. );
  1503. $query->select();
  1504. $resultSet = $this->getMock('\Cake\ORM\ResultSet', [], [$query, null]);
  1505. $query->expects($this->once())
  1506. ->method('all')
  1507. ->will($this->returnValue($resultSet));
  1508. $resultSet->expects($this->once())
  1509. ->method($method)
  1510. ->with($arg, 'extra')
  1511. ->will($this->returnValue(new \Cake\Collection\Collection([])));
  1512. $this->assertInstanceOf(
  1513. '\Cake\Collection\Collection',
  1514. $query->{$method}($arg, 'extra')
  1515. );
  1516. }
  1517. /**
  1518. * Tests that calling an inexistent method in query throws an
  1519. * exception
  1520. *
  1521. * @expectedException \BadMethodCallException
  1522. * @expectedExceptionMessage Unknown method "derpFilter"
  1523. * @return void
  1524. */
  1525. public function testCollectionProxyBadMethod()
  1526. {
  1527. TableRegistry::get('articles')->find('all')->derpFilter();
  1528. }
  1529. /**
  1530. * cache() should fail on non select queries.
  1531. *
  1532. * @expectedException \RuntimeException
  1533. * @return void
  1534. */
  1535. public function testCacheErrorOnNonSelect()
  1536. {
  1537. $table = TableRegistry::get('articles', ['table' => 'articles']);
  1538. $query = new Query($this->connection, $table);
  1539. $query->insert(['test']);
  1540. $query->cache('my_key');
  1541. }
  1542. /**
  1543. * Integration test for query caching.
  1544. *
  1545. * @return void
  1546. */
  1547. public function testCacheReadIntegration()
  1548. {
  1549. $query = $this->getMock(
  1550. '\Cake\ORM\Query',
  1551. ['execute'],
  1552. [$this->connection, $this->table]
  1553. );
  1554. $resultSet = $this->getMock('\Cake\ORM\ResultSet', [], [$query, null]);
  1555. $query->expects($this->never())
  1556. ->method('execute');
  1557. $cacher = $this->getMock('Cake\Cache\CacheEngine');
  1558. $cacher->expects($this->once())
  1559. ->method('read')
  1560. ->with('my_key')
  1561. ->will($this->returnValue($resultSet));
  1562. $query->cache('my_key', $cacher)
  1563. ->where(['id' => 1]);
  1564. $results = $query->all();
  1565. $this->assertSame($resultSet, $results);
  1566. }
  1567. /**
  1568. * Integration test for query caching.
  1569. *
  1570. * @return void
  1571. */
  1572. public function testCacheWriteIntegration()
  1573. {
  1574. $table = TableRegistry::get('Articles');
  1575. $query = new Query($this->connection, $table);
  1576. $query->select(['id', 'title']);
  1577. $cacher = $this->getMock('Cake\Cache\CacheEngine');
  1578. $cacher->expects($this->once())
  1579. ->method('write')
  1580. ->with(
  1581. 'my_key',
  1582. $this->isInstanceOf('Cake\Datasource\ResultSetInterface')
  1583. );
  1584. $query->cache('my_key', $cacher)
  1585. ->where(['id' => 1]);
  1586. $query->all();
  1587. }
  1588. /**
  1589. * Integration test to show filtering associations using contain and a closure
  1590. *
  1591. * @return void
  1592. */
  1593. public function testContainWithClosure()
  1594. {
  1595. $table = TableRegistry::get('authors');
  1596. $table->hasMany('articles');
  1597. $query = new Query($this->connection, $table);
  1598. $query
  1599. ->select()
  1600. ->contain(['articles' => function ($q) {
  1601. return $q->where(['articles.id' => 1]);
  1602. }]);
  1603. $ids = [];
  1604. foreach ($query as $entity) {
  1605. foreach ((array)$entity->articles as $article) {
  1606. $ids[] = $article->id;
  1607. }
  1608. }
  1609. $this->assertEquals([1], array_unique($ids));
  1610. }
  1611. /**
  1612. * Integration test to ensure that filtering associations with the queryBuilder
  1613. * option works.
  1614. *
  1615. * @expectedException \RuntimeException
  1616. * @return void
  1617. */
  1618. public function testContainWithQueryBuilderHasManyError()
  1619. {
  1620. $table = TableRegistry::get('Authors');
  1621. $table->hasMany('Articles');
  1622. $query = new Query($this->connection, $table);
  1623. $query->select()
  1624. ->contain([
  1625. 'Articles' => [
  1626. 'foreignKey' => false,
  1627. 'queryBuilder' => function ($q) {
  1628. return $q->where(['articles.id' => 1]);
  1629. }
  1630. ]
  1631. ]);
  1632. $query->toArray();
  1633. }
  1634. /**
  1635. * Integration test to ensure that filtering associations with the queryBuilder
  1636. * option works.
  1637. *
  1638. * @return void
  1639. */
  1640. public function testContainWithQueryBuilderJoinableAssociation()
  1641. {
  1642. $table = TableRegistry::get('Authors');
  1643. $table->hasOne('Articles');
  1644. $query = new Query($this->connection, $table);
  1645. $query->select()
  1646. ->contain([
  1647. 'Articles' => [
  1648. 'foreignKey' => false,
  1649. 'queryBuilder' => function ($q) {
  1650. return $q->where(['Articles.id' => 1]);
  1651. }
  1652. ]
  1653. ]);
  1654. $result = $query->toArray();
  1655. $this->assertEquals(1, $result[0]->article->id);
  1656. $this->assertEquals(1, $result[1]->article->id);
  1657. $articles = TableRegistry::get('Articles');
  1658. $articles->belongsTo('Authors');
  1659. $query = new Query($this->connection, $articles);
  1660. $query->select()
  1661. ->contain([
  1662. 'Authors' => [
  1663. 'foreignKey' => false,
  1664. 'queryBuilder' => function ($q) {
  1665. return $q->where(['Authors.id' => 1]);
  1666. }
  1667. ]
  1668. ]);
  1669. $result = $query->toArray();
  1670. $this->assertEquals(1, $result[0]->author->id);
  1671. }
  1672. /**
  1673. * Tests the formatResults method
  1674. *
  1675. * @return void
  1676. */
  1677. public function testFormatResults()
  1678. {
  1679. $callback1 = function () {
  1680. };
  1681. $callback2 = function () {
  1682. };
  1683. $table = TableRegistry::get('authors');
  1684. $query = new Query($this->connection, $table);
  1685. $this->assertSame($query, $query->formatResults($callback1));
  1686. $this->assertSame([$callback1], $query->formatResults());
  1687. $this->assertSame($query, $query->formatResults($callback2));
  1688. $this->assertSame([$callback1, $callback2], $query->formatResults());
  1689. $query->formatResults($callback2, true);
  1690. $this->assertSame([$callback2], $query->formatResults());
  1691. $query->formatResults(null, true);
  1692. $this->assertSame([], $query->formatResults());
  1693. $query->formatResults($callback1);
  1694. $query->formatResults($callback2, $query::PREPEND);
  1695. $this->assertSame([$callback2, $callback1], $query->formatResults());
  1696. }
  1697. /**
  1698. * Test fetching results from a qurey with a custom formatter
  1699. *
  1700. * @return void
  1701. */
  1702. public function testQueryWithFormatter()
  1703. {
  1704. $table = TableRegistry::get('authors');
  1705. $query = new Query($this->connection, $table);
  1706. $query->select()->formatResults(function ($results) {
  1707. $this->assertInstanceOf('Cake\ORM\ResultSet', $results);
  1708. return $results->indexBy('id');
  1709. });
  1710. $this->assertEquals([1, 2, 3, 4], array_keys($query->toArray()));
  1711. }
  1712. /**
  1713. * Test fetching results from a qurey with a two custom formatters
  1714. *
  1715. * @return void
  1716. */
  1717. public function testQueryWithStackedFormatters()
  1718. {
  1719. $table = TableRegistry::get('authors');
  1720. $query = new Query($this->connection, $table);
  1721. $query->select()->formatResults(function ($results) {
  1722. $this->assertInstanceOf('Cake\ORM\ResultSet', $results);
  1723. return $results->indexBy('id');
  1724. });
  1725. $query->formatResults(function ($results) {
  1726. return $results->extract('name');
  1727. });
  1728. $expected = [
  1729. 1 => 'mariano',
  1730. 2 => 'nate',
  1731. 3 => 'larry',
  1732. 4 => 'garrett'
  1733. ];
  1734. $this->assertEquals($expected, $query->toArray());
  1735. }
  1736. /**
  1737. * Tests that getting results from a query having a contained association
  1738. * will not attach joins twice if count() is called on it afterwards
  1739. *
  1740. * @return void
  1741. */
  1742. public function testCountWithContainCallingAll()
  1743. {
  1744. $table = TableRegistry::get('articles');
  1745. $table->belongsTo('authors');
  1746. $query = $table->find()
  1747. ->select(['id', 'title'])
  1748. ->contain('authors')
  1749. ->limit(2);
  1750. $results = $query->all();
  1751. $this->assertCount(2, $results);
  1752. $this->assertEquals(3, $query->count());
  1753. }
  1754. /**
  1755. * Tests that it is possible to apply formatters inside the query builder
  1756. * for belongsTo associations
  1757. *
  1758. * @return void
  1759. */
  1760. public function testFormatBelongsToRecords()
  1761. {
  1762. $table = TableRegistry::get('articles');
  1763. $table->belongsTo('authors');
  1764. $query = $table->find()
  1765. ->contain(['authors' => function ($q) {
  1766. return $q
  1767. ->formatResults(function ($authors) {
  1768. return $authors->map(function ($author) {
  1769. $author->idCopy = $author->id;
  1770. return $author;
  1771. });
  1772. })
  1773. ->formatResults(function ($authors) {
  1774. return $authors->map(function ($author) {
  1775. $author->idCopy = $author->idCopy + 2;
  1776. return $author;
  1777. });
  1778. });
  1779. }]);
  1780. $query->formatResults(function ($results) {
  1781. return $results->combine('id', 'author.idCopy');
  1782. });
  1783. $results = $query->toArray();
  1784. $expected = [1 => 3, 2 => 5, 3 => 3];
  1785. $this->assertEquals($expected, $results);
  1786. }
  1787. /**
  1788. * Tests it is possible to apply formatters to deep relations.
  1789. *
  1790. * @return void
  1791. */
  1792. public function testFormatDeepAssocationRecords()
  1793. {
  1794. $table = TableRegistry::get('ArticlesTags');
  1795. $table->belongsTo('Articles');
  1796. $table->association('Articles')->target()->belongsTo('Authors');
  1797. $builder = function ($q) {
  1798. return $q
  1799. ->formatResults(function ($results) {
  1800. return $results->map(function ($result) {
  1801. $result->idCopy = $result->id;
  1802. return $result;
  1803. });
  1804. })
  1805. ->formatResults(function ($results) {
  1806. return $results->map(function ($result) {
  1807. $result->idCopy = $result->idCopy + 2;
  1808. return $result;
  1809. });
  1810. });
  1811. };
  1812. $query = $table->find()
  1813. ->contain(['Articles' => $builder, 'Articles.Authors' => $builder])
  1814. ->order(['Articles.id' => 'ASC']);
  1815. $query->formatResults(function ($results) {
  1816. return $results->map(function ($row) {
  1817. return sprintf(
  1818. '%s - %s - %s',
  1819. $row->tag_id,
  1820. $row->article->idCopy,
  1821. $row->article->author->idCopy
  1822. );
  1823. });
  1824. });
  1825. $expected = ['1 - 3 - 3', '2 - 3 - 3', '1 - 4 - 5', '3 - 4 - 5'];
  1826. $this->assertEquals($expected, $query->toArray());
  1827. }
  1828. /**
  1829. * Tests that formatters cna be applied to deep associations that are fetched using
  1830. * additional queries
  1831. *
  1832. * @return void
  1833. */
  1834. public function testFormatDeepDistantAssociationRecords()
  1835. {
  1836. $table = TableRegistry::get('authors');
  1837. $table->hasMany('articles');
  1838. $articles = $table->association('articles')->target();
  1839. $articles->hasMany('articlesTags');
  1840. $articles->association('articlesTags')->target()->belongsTo('tags');
  1841. $query = $table->find()->contain(['articles.articlesTags.tags' => function ($q) {
  1842. return $q->formatResults(function ($results) {
  1843. return $results->map(function ($tag) {
  1844. $tag->name .= ' - visited';
  1845. return $tag;
  1846. });
  1847. });
  1848. }]);
  1849. $query->mapReduce(function ($row, $key, $mr) {
  1850. foreach ((array)$row->articles as $article) {
  1851. foreach ((array)$article->articles_tags as $articleTag) {
  1852. $mr->emit($articleTag->tag->name);
  1853. }
  1854. }
  1855. });
  1856. $expected = ['tag1 - visited', 'tag2 - visited', 'tag1 - visited', 'tag3 - visited'];
  1857. $this->assertEquals($expected, $query->toArray());
  1858. }
  1859. /**
  1860. * Tests that custom finders are applied to associations when using the proxies
  1861. *
  1862. * @return void
  1863. */
  1864. public function testCustomFinderInBelongsTo()
  1865. {
  1866. $table = TableRegistry::get('ArticlesTags');
  1867. $table->belongsTo('Articles', [
  1868. 'className' => 'TestApp\Model\Table\ArticlesTable',
  1869. 'finder' => 'published'
  1870. ]);
  1871. $result = $table->find()->contain('Articles');
  1872. $this->assertCount(4, $result->extract('article')->filter()->toArray());
  1873. $table->Articles->updateAll(['published' => 'N'], ['1 = 1']);
  1874. $result = $table->find()->contain('Articles');
  1875. $this->assertCount(0, $result->extract('article')->filter()->toArray());
  1876. }
  1877. /**
  1878. * Tests that it is possible to attach more association when using a query
  1879. * builder for other associations
  1880. *
  1881. * @return void
  1882. */
  1883. public function testContainInAssociationQuery()
  1884. {
  1885. $table = TableRegistry::get('ArticlesTags');
  1886. $table->belongsTo('Articles');
  1887. $table->association('Articles')->target()->belongsTo('Authors');
  1888. $query = $table->find()
  1889. ->order(['Articles.id' => 'ASC'])
  1890. ->contain(['Articles' => function ($q) {
  1891. return $q->contain('Authors');
  1892. }]);
  1893. $results = $query->extract('article.author.name')->toArray();
  1894. $expected = ['mariano', 'mariano', 'larry', 'larry'];
  1895. $this->assertEquals($expected, $results);
  1896. }
  1897. /**
  1898. * Tests that it is possible to apply more `matching` conditions inside query
  1899. * builders for associations
  1900. *
  1901. * @return void
  1902. */
  1903. public function testContainInAssociationMatching()
  1904. {
  1905. $table = TableRegistry::get('authors');
  1906. $table->hasMany('articles');
  1907. $articles = $table->association('articles')->target();
  1908. $articles->hasMany('articlesTags');
  1909. $articles->association('articlesTags')->target()->belongsTo('tags');
  1910. $query = $table->find()->matching('articles.articlesTags', function ($q) {
  1911. return $q->matching('tags', function ($q) {
  1912. return $q->where(['tags.name' => 'tag3']);
  1913. });
  1914. });
  1915. $results = $query->toArray();
  1916. $this->assertCount(1, $results);
  1917. $this->assertEquals('tag3', $results[0]->_matchingData['tags']->name);
  1918. }
  1919. /**
  1920. * Tests __debugInfo
  1921. *
  1922. * @return void
  1923. */
  1924. public function testDebugInfo()
  1925. {
  1926. $table = TableRegistry::get('authors');
  1927. $table->hasMany('articles');
  1928. $query = $table->find()
  1929. ->where(['id > ' => 1])
  1930. ->bufferResults(false)
  1931. ->hydrate(false)
  1932. ->matching('articles')
  1933. ->applyOptions(['foo' => 'bar'])
  1934. ->formatResults(function ($results) {
  1935. return $results;
  1936. })
  1937. ->mapReduce(function ($item, $key, $mr) {
  1938. $mr->emit($item);
  1939. });
  1940. $expected = [
  1941. 'sql' => $query->sql(),
  1942. 'params' => $query->valueBinder()->bindings(),
  1943. 'defaultTypes' => [
  1944. 'authors.id' => 'integer',
  1945. 'id' => 'integer',
  1946. 'authors.name' => 'string',
  1947. 'name' => 'string'
  1948. ],
  1949. 'decorators' => 0,
  1950. 'executed' => false,
  1951. 'hydrate' => false,
  1952. 'buffered' => false,
  1953. 'formatters' => 1,
  1954. 'mapReducers' => 1,
  1955. 'contain' => [],
  1956. 'matching' => [
  1957. 'articles' => [
  1958. 'queryBuilder' => null,
  1959. 'matching' => true
  1960. ]
  1961. ],
  1962. 'extraOptions' => ['foo' => 'bar'],
  1963. 'repository' => $table
  1964. ];
  1965. $this->assertSame($expected, $query->__debugInfo());
  1966. }
  1967. /**
  1968. * Tests that the eagerLoaded function works and is transmitted correctly to eagerly
  1969. * loaded associations
  1970. *
  1971. * @return void
  1972. */
  1973. public function testEagerLoaded()
  1974. {
  1975. $table = TableRegistry::get('authors');
  1976. $table->hasMany('articles');
  1977. $query = $table->find()->contain(['articles' => function ($q) {
  1978. $this->assertTrue($q->eagerLoaded());
  1979. return $q;
  1980. }]);
  1981. $this->assertFalse($query->eagerLoaded());
  1982. $table->eventManager()->attach(function ($e, $q, $o, $primary) {
  1983. $this->assertTrue($primary);
  1984. }, 'Model.beforeFind');
  1985. TableRegistry::get('articles')
  1986. ->eventManager()->attach(function ($e, $q, $o, $primary) {
  1987. $this->assertFalse($primary);
  1988. }, 'Model.beforeFind');
  1989. $query->all();
  1990. }
  1991. /**
  1992. * Tests that columns from manual joins are also contained in the result set
  1993. *
  1994. * @return void
  1995. */
  1996. public function testColumnsFromJoin()
  1997. {
  1998. $table = TableRegistry::get('articles');
  1999. $results = $table->find()
  2000. ->select(['title', 'person.name'])
  2001. ->join([
  2002. 'person' => [
  2003. 'table' => 'authors',
  2004. 'conditions' => ['person.id = articles.author_id']
  2005. ]
  2006. ])
  2007. ->order(['articles.id' => 'ASC'])
  2008. ->hydrate(false)
  2009. ->toArray();
  2010. $expected = [
  2011. ['title' => 'First Article', 'person' => ['name' => 'mariano']],
  2012. ['title' => 'Second Article', 'person' => ['name' => 'larry']],
  2013. ['title' => 'Third Article', 'person' => ['name' => 'mariano']],
  2014. ];
  2015. $this->assertSame($expected, $results);
  2016. }
  2017. /**
  2018. * Tests that it is possible to use the same association aliases in the association
  2019. * chain for contain
  2020. *
  2021. * @dataProvider internalStategiesProvider
  2022. * @return void
  2023. */
  2024. public function testRepeatedAssociationAliases($strategy)
  2025. {
  2026. $table = TableRegistry::get('ArticlesTags');
  2027. $table->belongsTo('Articles', ['strategy' => $strategy]);
  2028. $table->belongsTo('Tags', ['strategy' => $strategy]);
  2029. TableRegistry::get('Tags')->belongsToMany('Articles');
  2030. $results = $table
  2031. ->find()
  2032. ->contain(['Articles', 'Tags.Articles'])
  2033. ->hydrate(false)
  2034. ->toArray();
  2035. $this->assertNotEmpty($results[0]['tag']['articles']);
  2036. $this->assertNotEmpty($results[0]['article']);
  2037. $this->assertNotEmpty($results[1]['tag']['articles']);
  2038. $this->assertNotEmpty($results[1]['article']);
  2039. $this->assertNotEmpty($results[2]['tag']['articles']);
  2040. $this->assertNotEmpty($results[2]['article']);
  2041. }
  2042. /**
  2043. * Tests that a hasOne association using the select strategy will still have the
  2044. * key present in the results when no match is found
  2045. *
  2046. * @return void
  2047. */
  2048. public function testAssociationKeyPresent()
  2049. {
  2050. $table = TableRegistry::get('Articles');
  2051. $table->hasOne('ArticlesTags', ['strategy' => 'select']);
  2052. $article = $table->find()->where(['id' => 3])
  2053. ->hydrate(false)
  2054. ->contain('ArticlesTags')
  2055. ->first();
  2056. $this->assertNull($article['articles_tag']);
  2057. }
  2058. /**
  2059. * Tests that queries can be serialized to JSON to get the results
  2060. *
  2061. * @return void
  2062. */
  2063. public function testJsonSerialize()
  2064. {
  2065. $table = TableRegistry::get('Articles');
  2066. $this->assertEquals(
  2067. json_encode($table->find()),
  2068. json_encode($table->find()->toArray())
  2069. );
  2070. }
  2071. /**
  2072. * Test that addFields() works in the basic case.
  2073. *
  2074. * @return void
  2075. */
  2076. public function testAutoFields()
  2077. {
  2078. $table = TableRegistry::get('Articles');
  2079. $result = $table->find('all')
  2080. ->select(['myField' => '(SELECT 20)'])
  2081. ->autoFields(true)
  2082. ->hydrate(false)
  2083. ->first();
  2084. $this->assertArrayHasKey('myField', $result);
  2085. $this->assertArrayHasKey('id', $result);
  2086. $this->assertArrayHasKey('title', $result);
  2087. }
  2088. /**
  2089. * Test autoFields with auto fields.
  2090. *
  2091. * @return void
  2092. */
  2093. public function testAutoFieldsWithAssociations()
  2094. {
  2095. $table = TableRegistry::get('Articles');
  2096. $table->belongsTo('Authors');
  2097. $result = $table->find()
  2098. ->select(['myField' => '(SELECT 2 + 2)'])
  2099. ->autoFields(true)
  2100. ->hydrate(false)
  2101. ->contain('Authors')
  2102. ->first();
  2103. $this->assertArrayHasKey('myField', $result);
  2104. $this->assertArrayHasKey('title', $result);
  2105. $this->assertArrayHasKey('author', $result);
  2106. $this->assertNotNull($result['author']);
  2107. $this->assertArrayHasKey('name', $result['author']);
  2108. }
  2109. /**
  2110. * Test autoFields in contain query builder
  2111. *
  2112. * @return void
  2113. */
  2114. public function testAutoFieldsWithContainQueryBuilder()
  2115. {
  2116. $table = TableRegistry::get('Articles');
  2117. $table->belongsTo('Authors');
  2118. $result = $table->find()
  2119. ->select(['myField' => '(SELECT 2 + 2)'])
  2120. ->autoFields(true)
  2121. ->hydrate(false)
  2122. ->contain(['Authors' => function ($q) {
  2123. return $q->select(['compute' => '(SELECT 2 + 20)'])
  2124. ->autoFields(true);
  2125. }])
  2126. ->first();
  2127. $this->assertArrayHasKey('myField', $result);
  2128. $this->assertArrayHasKey('title', $result);
  2129. $this->assertArrayHasKey('author', $result);
  2130. $this->assertNotNull($result['author']);
  2131. $this->assertArrayHasKey('name', $result['author']);
  2132. $this->assertArrayHasKey('compute', $result);
  2133. }
  2134. /**
  2135. * Test that autofields works with count()
  2136. *
  2137. * @return void
  2138. */
  2139. public function testAutoFieldsCount()
  2140. {
  2141. $table = TableRegistry::get('Articles');
  2142. $result = $table->find()
  2143. ->select(['myField' => '(SELECT (2 + 2))'])
  2144. ->autoFields(true)
  2145. ->count();
  2146. $this->assertEquals(3, $result);
  2147. }
  2148. /**
  2149. * test that cleanCopy makes a cleaned up clone.
  2150. *
  2151. * @return void
  2152. */
  2153. public function testCleanCopy()
  2154. {
  2155. $table = TableRegistry::get('Articles');
  2156. $table->hasMany('Comments');
  2157. $query = $table->find();
  2158. $query->offset(10)
  2159. ->limit(1)
  2160. ->order(['Articles.id' => 'DESC'])
  2161. ->contain(['Comments']);
  2162. $copy = $query->cleanCopy();
  2163. $this->assertNotSame($copy, $query);
  2164. $this->assertNull($copy->clause('offset'));
  2165. $this->assertNull($copy->clause('limit'));
  2166. $this->assertNull($copy->clause('order'));
  2167. }
  2168. /**
  2169. * test that cleanCopy makes a cleaned up clone with a beforeFind.
  2170. *
  2171. * @return void
  2172. */
  2173. public function testCleanCopyBeforeFind()
  2174. {
  2175. $table = TableRegistry::get('Articles');
  2176. $table->hasMany('Comments');
  2177. $table->eventManager()
  2178. ->attach(function ($event, $query) {
  2179. $query
  2180. ->limit(5)
  2181. ->order(['Articles.title' => 'DESC']);
  2182. }, 'Model.beforeFind');
  2183. $query = $table->find();
  2184. $query->offset(10)
  2185. ->limit(1)
  2186. ->order(['Articles.id' => 'DESC'])
  2187. ->contain(['Comments']);
  2188. $copy = $query->cleanCopy();
  2189. $this->assertNotSame($copy, $query);
  2190. $this->assertNull($copy->clause('offset'));
  2191. $this->assertNull($copy->clause('limit'));
  2192. $this->assertNull($copy->clause('order'));
  2193. }
  2194. /**
  2195. * Test that finder options sent through via contain are sent to custom finder.
  2196. *
  2197. * @return void
  2198. */
  2199. public function testContainFinderCanSpecifyOptions()
  2200. {
  2201. $table = TableRegistry::get('Articles');
  2202. $table->belongsTo(
  2203. 'Authors',
  2204. ['className' => 'TestApp\Model\Table\AuthorsTable']
  2205. );
  2206. $authorId = 1;
  2207. $resultWithoutAuthor = $table->find('all')
  2208. ->where(['Articles.author_id' => $authorId])
  2209. ->contain([
  2210. 'Authors' => [
  2211. 'finder' => ['byAuthor' => ['author_id' => 2]]
  2212. ]
  2213. ]);
  2214. $resultWithAuthor = $table->find('all')
  2215. ->where(['Articles.author_id' => $authorId])
  2216. ->contain([
  2217. 'Authors' => [
  2218. 'finder' => ['byAuthor' => ['author_id' => $authorId]]
  2219. ]
  2220. ]);
  2221. $this->assertEmpty($resultWithoutAuthor->first()['author']);
  2222. $this->assertEquals($authorId, $resultWithAuthor->first()['author']['id']);
  2223. }
  2224. /**
  2225. * Tests that it is possible to bind arguments to a query and it will return the right
  2226. * results
  2227. *
  2228. * @return void
  2229. */
  2230. public function testCustomBindings()
  2231. {
  2232. $table = TableRegistry::get('Articles');
  2233. $query = $table->find()->where(['id >' => 1]);
  2234. $query->where(function ($exp) {
  2235. return $exp->add('author_id = :author');
  2236. });
  2237. $query->bind(':author', 1, 'integer');
  2238. $this->assertEquals(1, $query->count());
  2239. $this->assertEquals(3, $query->first()->id);
  2240. }
  2241. /**
  2242. * Tests that it is possible to pass a custom join type for an association when
  2243. * using contain
  2244. *
  2245. * @return void
  2246. */
  2247. public function testContainWithCustomJoinType()
  2248. {
  2249. $table = TableRegistry::get('Articles');
  2250. $table->belongsTo('Authors');
  2251. $articles = $table->find()
  2252. ->contain([
  2253. 'Authors' => [
  2254. 'joinType' => 'inner',
  2255. 'conditions' => ['Authors.id' => 3]
  2256. ]
  2257. ])
  2258. ->toArray();
  2259. $this->assertCount(1, $articles);
  2260. $this->assertEquals(3, $articles[0]->author->id);
  2261. }
  2262. /**
  2263. * Tests that it is possible to override the contain strategy using the
  2264. * containments array. In this case, no inner join will be made and for that
  2265. * reason, the parent association will not be filtered as the strategy changed
  2266. * from join to select.
  2267. *
  2268. * @return void
  2269. */
  2270. public function testContainWithStrategyOverride()
  2271. {
  2272. $table = TableRegistry::get('Articles');
  2273. $table->belongsTo('Authors', [
  2274. 'joinType' => 'INNER'
  2275. ]);
  2276. $articles = $table->find()
  2277. ->contain([
  2278. 'Authors' => [
  2279. 'strategy' => 'select',
  2280. 'conditions' => ['Authors.id' => 3]
  2281. ]
  2282. ])
  2283. ->toArray();
  2284. $this->assertCount(3, $articles);
  2285. $this->assertEquals(3, $articles[1]->author->id);
  2286. $this->assertNull($articles[0]->author);
  2287. $this->assertNull($articles[2]->author);
  2288. }
  2289. /**
  2290. * Tests that it is possible to call matching and contain on the same
  2291. * association.
  2292. *
  2293. * @return void
  2294. */
  2295. public function testMatchingWithContain()
  2296. {
  2297. $query = new Query($this->connection, $this->table);
  2298. $table = TableRegistry::get('authors');
  2299. $table->hasMany('articles');
  2300. TableRegistry::get('articles')->belongsToMany('tags');
  2301. $result = $query->repository($table)
  2302. ->select()
  2303. ->matching('articles.tags', function ($q) {
  2304. return $q->where(['tags.id' => 2]);
  2305. })
  2306. ->contain('articles')
  2307. ->first();
  2308. $this->assertEquals(1, $result->id);
  2309. $this->assertCount(2, $result->articles);
  2310. $this->assertEquals(2, $result->_matchingData['tags']->id);
  2311. }
  2312. /**
  2313. * Tests that it is possible to call matching and contain on the same
  2314. * association with only one level of depth.
  2315. *
  2316. * @return void
  2317. */
  2318. public function testNotSoFarMatchingWithContainOnTheSameAssociation()
  2319. {
  2320. $table = TableRegistry::get('articles');
  2321. $table->belongsToMany('tags');
  2322. $result = $table->find()
  2323. ->matching('tags', function ($q) {
  2324. return $q->where(['tags.id' => 2]);
  2325. })
  2326. ->contain('tags')
  2327. ->first();
  2328. $this->assertEquals(1, $result->id);
  2329. $this->assertCount(2, $result->tags);
  2330. $this->assertEquals(2, $result->_matchingData['tags']->id);
  2331. }
  2332. }