EagerLoaderTest.php 18 KB

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