EagerLoaderTest.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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\QueryExpression;
  18. use Cake\Database\TypeMap;
  19. use Cake\Datasource\ConnectionManager;
  20. use Cake\ORM\EagerLoader;
  21. use Cake\ORM\Query;
  22. use Cake\ORM\TableRegistry;
  23. use Cake\TestSuite\TestCase;
  24. /**
  25. * Tests EagerLoader
  26. *
  27. */
  28. class EagerLoaderTest extends TestCase
  29. {
  30. /**
  31. * setUp method
  32. *
  33. * @return void
  34. */
  35. public function setUp()
  36. {
  37. parent::setUp();
  38. $this->connection = ConnectionManager::get('test');
  39. $schema = [
  40. 'id' => ['type' => 'integer'],
  41. '_constraints' => [
  42. 'primary' => ['type' => 'primary', 'columns' => ['id']]
  43. ]
  44. ];
  45. $schema1 = [
  46. 'id' => ['type' => 'integer'],
  47. 'name' => ['type' => 'string'],
  48. 'phone' => ['type' => 'string'],
  49. '_constraints' => [
  50. 'primary' => ['type' => 'primary', 'columns' => ['id']]
  51. ]
  52. ];
  53. $schema2 = [
  54. 'id' => ['type' => 'integer'],
  55. 'total' => ['type' => 'string'],
  56. 'placed' => ['type' => 'datetime'],
  57. '_constraints' => [
  58. 'primary' => ['type' => 'primary', 'columns' => ['id']]
  59. ]
  60. ];
  61. $this->table = $table = TableRegistry::get('foo', ['schema' => $schema]);
  62. $clients = TableRegistry::get('clients', ['schema' => $schema1]);
  63. $orders = TableRegistry::get('orders', ['schema' => $schema2]);
  64. $companies = TableRegistry::get('companies', ['schema' => $schema, 'table' => 'organizations']);
  65. $orderTypes = TableRegistry::get('orderTypes', ['schema' => $schema]);
  66. $stuff = TableRegistry::get('stuff', ['schema' => $schema, 'table' => 'things']);
  67. $stuffTypes = TableRegistry::get('stuffTypes', ['schema' => $schema]);
  68. $categories = TableRegistry::get('categories', ['schema' => $schema]);
  69. $table->belongsTo('clients');
  70. $clients->hasOne('orders');
  71. $clients->belongsTo('companies');
  72. $orders->belongsTo('orderTypes');
  73. $orders->hasOne('stuff');
  74. $stuff->belongsTo('stuffTypes');
  75. $companies->belongsTo('categories');
  76. $this->clientsTypeMap = new TypeMap([
  77. 'clients.id' => 'integer',
  78. 'id' => 'integer',
  79. 'clients.name' => 'string',
  80. 'name' => 'string',
  81. 'clients.phone' => 'string',
  82. 'phone' => 'string',
  83. 'clients__id' => 'integer',
  84. 'clients__name' => 'string',
  85. 'clients__phone' => 'string',
  86. ]);
  87. $this->ordersTypeMap = new TypeMap([
  88. 'orders.id' => 'integer',
  89. 'id' => 'integer',
  90. 'orders.total' => 'string',
  91. 'total' => 'string',
  92. 'orders.placed' => 'datetime',
  93. 'placed' => 'datetime',
  94. 'orders__id' => 'integer',
  95. 'orders__total' => 'string',
  96. 'orders__placed' => 'datetime',
  97. ]);
  98. $this->orderTypesTypeMap = new TypeMap([
  99. 'orderTypes.id' => 'integer',
  100. 'id' => 'integer',
  101. 'orderTypes__id' => 'integer',
  102. ]);
  103. $this->stuffTypeMap = new TypeMap([
  104. 'stuff.id' => 'integer',
  105. 'id' => 'integer',
  106. 'stuff__id' => 'integer',
  107. ]);
  108. $this->stuffTypesTypeMap = new TypeMap([
  109. 'stuffTypes.id' => 'integer',
  110. 'id' => 'integer',
  111. 'stuffTypes__id' => 'integer',
  112. ]);
  113. $this->companiesTypeMap = new TypeMap([
  114. 'companies.id' => 'integer',
  115. 'id' => 'integer',
  116. 'companies__id' => 'integer',
  117. ]);
  118. $this->categoriesTypeMap = new TypeMap([
  119. 'categories.id' => 'integer',
  120. 'id' => 'integer',
  121. 'categories__id' => 'integer',
  122. ]);
  123. }
  124. /**
  125. * tearDown method
  126. *
  127. * @return void
  128. */
  129. public function tearDown()
  130. {
  131. parent::tearDown();
  132. TableRegistry::clear();
  133. }
  134. /**
  135. * Tests that fully defined belongsTo and hasOne relationships are joined correctly
  136. *
  137. * @return void
  138. */
  139. public function testContainToJoinsOneLevel()
  140. {
  141. $contains = [
  142. 'clients' => [
  143. 'orders' => [
  144. 'orderTypes',
  145. 'stuff' => ['stuffTypes']
  146. ],
  147. 'companies' => [
  148. 'foreignKey' => 'organization_id',
  149. 'categories'
  150. ]
  151. ]
  152. ];
  153. $query = $this->getMock('\Cake\ORM\Query', ['join'], [$this->connection, $this->table]);
  154. $query->typeMap($this->clientsTypeMap);
  155. $query->expects($this->at(0))->method('join')
  156. ->with(['clients' => [
  157. 'table' => 'clients',
  158. 'type' => 'LEFT',
  159. 'conditions' => new QueryExpression([
  160. ['clients.id' => new IdentifierExpression('foo.client_id')],
  161. ], new TypeMap($this->clientsTypeMap->defaults()))
  162. ]])
  163. ->will($this->returnValue($query));
  164. $query->expects($this->at(1))->method('join')
  165. ->with(['orders' => [
  166. 'table' => 'orders',
  167. 'type' => 'LEFT',
  168. 'conditions' => new QueryExpression([
  169. ['clients.id' => new IdentifierExpression('orders.client_id')]
  170. ], $this->ordersTypeMap)
  171. ]])
  172. ->will($this->returnValue($query));
  173. $query->expects($this->at(2))->method('join')
  174. ->with(['orderTypes' => [
  175. 'table' => 'order_types',
  176. 'type' => 'LEFT',
  177. 'conditions' => new QueryExpression([
  178. ['orderTypes.id' => new IdentifierExpression('orders.order_type_id')]
  179. ], $this->orderTypesTypeMap)
  180. ]])
  181. ->will($this->returnValue($query));
  182. $query->expects($this->at(3))->method('join')
  183. ->with(['stuff' => [
  184. 'table' => 'things',
  185. 'type' => 'LEFT',
  186. 'conditions' => new QueryExpression([
  187. ['orders.id' => new IdentifierExpression('stuff.order_id')]
  188. ], $this->stuffTypeMap)
  189. ]])
  190. ->will($this->returnValue($query));
  191. $query->expects($this->at(4))->method('join')
  192. ->with(['stuffTypes' => [
  193. 'table' => 'stuff_types',
  194. 'type' => 'LEFT',
  195. 'conditions' => new QueryExpression([
  196. ['stuffTypes.id' => new IdentifierExpression('stuff.stuff_type_id')]
  197. ], $this->stuffTypesTypeMap)
  198. ]])
  199. ->will($this->returnValue($query));
  200. $query->expects($this->at(5))->method('join')
  201. ->with(['companies' => [
  202. 'table' => 'organizations',
  203. 'type' => 'LEFT',
  204. 'conditions' => new QueryExpression([
  205. ['companies.id' => new IdentifierExpression('clients.organization_id')]
  206. ], $this->companiesTypeMap)
  207. ]])
  208. ->will($this->returnValue($query));
  209. $query->expects($this->at(6))->method('join')
  210. ->with(['categories' => [
  211. 'table' => 'categories',
  212. 'type' => 'LEFT',
  213. 'conditions' => new QueryExpression([
  214. ['categories.id' => new IdentifierExpression('companies.category_id')]
  215. ], $this->categoriesTypeMap)
  216. ]])
  217. ->will($this->returnValue($query));
  218. $loader = new EagerLoader;
  219. $loader->contain($contains);
  220. $query->select('foo.id')->eagerLoader($loader)->sql();
  221. }
  222. /**
  223. * Tests setting containments using dot notation, additionally proves that options
  224. * are not overwritten when combining dot notation and array notation
  225. *
  226. * @return void
  227. */
  228. public function testContainDotNotation()
  229. {
  230. $loader = new EagerLoader;
  231. $loader->contain([
  232. 'clients.orders.stuff',
  233. 'clients.companies.categories' => ['conditions' => ['a >' => 1]]
  234. ]);
  235. $expected = [
  236. 'clients' => [
  237. 'orders' => [
  238. 'stuff' => []
  239. ],
  240. 'companies' => [
  241. 'categories' => [
  242. 'conditions' => ['a >' => 1]
  243. ]
  244. ]
  245. ]
  246. ];
  247. $this->assertEquals($expected, $loader->contain());
  248. $loader->contain([
  249. 'clients.orders' => ['fields' => ['a', 'b']],
  250. 'clients' => ['sort' => ['a' => 'desc']],
  251. ]);
  252. $expected['clients']['orders'] += ['fields' => ['a', 'b']];
  253. $expected['clients'] += ['sort' => ['a' => 'desc']];
  254. $this->assertEquals($expected, $loader->contain());
  255. }
  256. /**
  257. * Tests that it is possible to pass a function as the array value for contain
  258. *
  259. * @return void
  260. */
  261. public function testContainClosure()
  262. {
  263. $builder = function ($query) {
  264. };
  265. $loader = new EagerLoader;
  266. $loader->contain([
  267. 'clients.orders.stuff' => ['fields' => ['a']],
  268. 'clients' => $builder
  269. ]);
  270. $expected = [
  271. 'clients' => [
  272. 'orders' => [
  273. 'stuff' => ['fields' => ['a']]
  274. ],
  275. 'queryBuilder' => $builder
  276. ]
  277. ];
  278. $this->assertEquals($expected, $loader->contain());
  279. $loader = new EagerLoader;
  280. $loader->contain([
  281. 'clients.orders.stuff' => ['fields' => ['a']],
  282. 'clients' => ['queryBuilder' => $builder]
  283. ]);
  284. $this->assertEquals($expected, $loader->contain());
  285. }
  286. /**
  287. * Tests that query builders are stacked
  288. *
  289. * @return void
  290. */
  291. public function testContainMergeBuilders()
  292. {
  293. $loader = new EagerLoader;
  294. $loader->contain([
  295. 'clients' => function ($query) {
  296. return $query->select(['a']);
  297. }
  298. ]);
  299. $loader->contain([
  300. 'clients' => function ($query) {
  301. return $query->select(['b']);
  302. }
  303. ]);
  304. $builder = $loader->contain()['clients']['queryBuilder'];
  305. $table = TableRegistry::get('foo');
  306. $query = new Query($this->connection, $table);
  307. $query = $builder($query);
  308. $this->assertEquals(['a', 'b'], $query->clause('select'));
  309. }
  310. /**
  311. * Test that fields for contained models are aliased and added to the select clause
  312. *
  313. * @return void
  314. */
  315. public function testContainToFieldsPredefined()
  316. {
  317. $contains = [
  318. 'clients' => [
  319. 'fields' => ['name', 'company_id', 'clients.telephone'],
  320. 'orders' => [
  321. 'fields' => ['total', 'placed']
  322. ]
  323. ]
  324. ];
  325. $table = TableRegistry::get('foo');
  326. $query = new Query($this->connection, $table);
  327. $loader = new EagerLoader;
  328. $loader->contain($contains);
  329. $query->select('foo.id');
  330. $loader->attachAssociations($query, $table, true);
  331. $select = $query->clause('select');
  332. $expected = [
  333. 'foo.id', 'clients__name' => 'clients.name',
  334. 'clients__company_id' => 'clients.company_id',
  335. 'clients__telephone' => 'clients.telephone',
  336. 'orders__total' => 'orders.total', 'orders__placed' => 'orders.placed'
  337. ];
  338. $this->assertEquals($expected, $select);
  339. }
  340. /**
  341. * Tests that default fields for associations are added to the select clause when
  342. * none is specified
  343. *
  344. * @return void
  345. */
  346. public function testContainToFieldsDefault()
  347. {
  348. $contains = ['clients' => ['orders']];
  349. $query = new Query($this->connection, $this->table);
  350. $query->select()->contain($contains)->sql();
  351. $select = $query->clause('select');
  352. $expected = [
  353. 'foo__id' => 'foo.id', 'clients__name' => 'clients.name',
  354. 'clients__id' => 'clients.id', 'clients__phone' => 'clients.phone',
  355. 'orders__id' => 'orders.id', 'orders__total' => 'orders.total',
  356. 'orders__placed' => 'orders.placed'
  357. ];
  358. $expected = $this->_quoteArray($expected);
  359. $this->assertEquals($expected, $select);
  360. $contains['clients']['fields'] = ['name'];
  361. $query = new Query($this->connection, $this->table);
  362. $query->select('foo.id')->contain($contains)->sql();
  363. $select = $query->clause('select');
  364. $expected = ['foo__id' => 'foo.id', 'clients__name' => 'clients.name'];
  365. $expected = $this->_quoteArray($expected);
  366. $this->assertEquals($expected, $select);
  367. $contains['clients']['fields'] = [];
  368. $contains['clients']['orders']['fields'] = false;
  369. $query = new Query($this->connection, $this->table);
  370. $query->select()->contain($contains)->sql();
  371. $select = $query->clause('select');
  372. $expected = [
  373. 'foo__id' => 'foo.id',
  374. 'clients__id' => 'clients.id',
  375. 'clients__name' => 'clients.name',
  376. 'clients__phone' => 'clients.phone',
  377. ];
  378. $expected = $this->_quoteArray($expected);
  379. $this->assertEquals($expected, $select);
  380. }
  381. /**
  382. * Check that normalizing contains checks alias names.
  383. *
  384. * @expectedException \InvalidArgumentException
  385. * @expectedExceptionMessage You have contained 'Clients' but that association was bound as 'clients'
  386. * @return void
  387. */
  388. public function testNormalizedChecksAliasNames()
  389. {
  390. $contains = ['Clients'];
  391. $loader = new EagerLoader;
  392. $loader->contain($contains);
  393. $loader->normalized($this->table);
  394. }
  395. /**
  396. * Tests that the path for gettings to a deep assocition is materialized in an
  397. * array key
  398. *
  399. * @return void
  400. */
  401. public function testNormalizedPath()
  402. {
  403. $contains = [
  404. 'clients' => [
  405. 'orders' => [
  406. 'orderTypes',
  407. 'stuff' => ['stuffTypes']
  408. ],
  409. 'companies' => [
  410. 'categories'
  411. ]
  412. ]
  413. ];
  414. $query = $this->getMock(
  415. '\Cake\ORM\Query',
  416. ['join'],
  417. [$this->connection, $this->table]
  418. );
  419. $loader = new EagerLoader;
  420. $loader->contain($contains);
  421. $normalized = $loader->normalized($this->table);
  422. $this->assertEquals('clients', $normalized['clients']->aliasPath());
  423. $this->assertEquals('client', $normalized['clients']->propertyPath());
  424. $assocs = $normalized['clients']->associations();
  425. $this->assertEquals('clients.orders', $assocs['orders']->aliasPath());
  426. $this->assertEquals('client.order', $assocs['orders']->propertyPath());
  427. $assocs = $assocs['orders']->associations();
  428. $this->assertEquals('clients.orders.orderTypes', $assocs['orderTypes']->aliasPath());
  429. $this->assertEquals('client.order.order_type', $assocs['orderTypes']->propertyPath());
  430. $this->assertEquals('clients.orders.stuff', $assocs['stuff']->aliasPath());
  431. $this->assertEquals('client.order.stuff', $assocs['stuff']->propertyPath());
  432. $assocs = $assocs['stuff']->associations();
  433. $this->assertEquals(
  434. 'clients.orders.stuff.stuffTypes',
  435. $assocs['stuffTypes']->aliasPath()
  436. );
  437. $this->assertEquals(
  438. 'client.order.stuff.stuff_type',
  439. $assocs['stuffTypes']->propertyPath()
  440. );
  441. }
  442. /**
  443. * Test clearing containments but not matching joins.
  444. *
  445. * @return void
  446. */
  447. public function testClearContain()
  448. {
  449. $contains = [
  450. 'clients' => [
  451. 'orders' => [
  452. 'orderTypes',
  453. 'stuff' => ['stuffTypes']
  454. ],
  455. 'companies' => [
  456. 'categories'
  457. ]
  458. ]
  459. ];
  460. $loader = new EagerLoader();
  461. $loader->contain($contains);
  462. $loader->matching('clients.addresses');
  463. $this->assertNull($loader->clearContain());
  464. $result = $loader->normalized($this->table);
  465. $this->assertEquals([], $result);
  466. $this->assertArrayHasKey('clients', $loader->matching());
  467. }
  468. /**
  469. * Helper function sued to quoted both keys and values in an array in case
  470. * the test suite is running with auto quoting enabled
  471. *
  472. * @param array $elements
  473. * @return array
  474. */
  475. protected function _quoteArray($elements)
  476. {
  477. if ($this->connection->driver()->autoQuoting()) {
  478. $quoter = function ($e) {
  479. return $this->connection->driver()->quoteIdentifier($e);
  480. };
  481. return array_combine(
  482. array_map($quoter, array_keys($elements)),
  483. array_map($quoter, array_values($elements))
  484. );
  485. }
  486. return $elements;
  487. }
  488. }