PageRenderTime 66ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/tests/TestCase/ORM/QueryTest.php

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