EagerLoaderTest.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\ORM;
  16. use Cake\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 setting containments using direct key value pairs works just as with key array.
  260. *
  261. * @return void
  262. */
  263. public function testContainKeyValueNotation()
  264. {
  265. $loader = new EagerLoader;
  266. $loader->contain([
  267. 'clients',
  268. 'companies' => 'categories',
  269. ]);
  270. $expected = [
  271. 'clients' => [
  272. ],
  273. 'companies' => [
  274. 'categories' => [
  275. ],
  276. ],
  277. ];
  278. $this->assertEquals($expected, $loader->contain());
  279. }
  280. /**
  281. * Tests that it is possible to pass a function as the array value for contain
  282. *
  283. * @return void
  284. */
  285. public function testContainClosure()
  286. {
  287. $builder = function ($query) {
  288. };
  289. $loader = new EagerLoader;
  290. $loader->contain([
  291. 'clients.orders.stuff' => ['fields' => ['a']],
  292. 'clients' => $builder
  293. ]);
  294. $expected = [
  295. 'clients' => [
  296. 'orders' => [
  297. 'stuff' => ['fields' => ['a']]
  298. ],
  299. 'queryBuilder' => $builder
  300. ]
  301. ];
  302. $this->assertEquals($expected, $loader->contain());
  303. $loader = new EagerLoader;
  304. $loader->contain([
  305. 'clients.orders.stuff' => ['fields' => ['a']],
  306. 'clients' => ['queryBuilder' => $builder]
  307. ]);
  308. $this->assertEquals($expected, $loader->contain());
  309. }
  310. /**
  311. * Tests that query builders are stacked
  312. *
  313. * @return void
  314. */
  315. public function testContainMergeBuilders()
  316. {
  317. $loader = new EagerLoader;
  318. $loader->contain([
  319. 'clients' => function ($query) {
  320. return $query->select(['a']);
  321. }
  322. ]);
  323. $loader->contain([
  324. 'clients' => function ($query) {
  325. return $query->select(['b']);
  326. }
  327. ]);
  328. $builder = $loader->contain()['clients']['queryBuilder'];
  329. $table = TableRegistry::get('foo');
  330. $query = new Query($this->connection, $table);
  331. $query = $builder($query);
  332. $this->assertEquals(['a', 'b'], $query->clause('select'));
  333. }
  334. /**
  335. * Test that fields for contained models are aliased and added to the select clause
  336. *
  337. * @return void
  338. */
  339. public function testContainToFieldsPredefined()
  340. {
  341. $contains = [
  342. 'clients' => [
  343. 'fields' => ['name', 'company_id', 'clients.telephone'],
  344. 'orders' => [
  345. 'fields' => ['total', 'placed']
  346. ]
  347. ]
  348. ];
  349. $table = TableRegistry::get('foo');
  350. $query = new Query($this->connection, $table);
  351. $loader = new EagerLoader;
  352. $loader->contain($contains);
  353. $query->select('foo.id');
  354. $loader->attachAssociations($query, $table, true);
  355. $select = $query->clause('select');
  356. $expected = [
  357. 'foo.id', 'clients__name' => 'clients.name',
  358. 'clients__company_id' => 'clients.company_id',
  359. 'clients__telephone' => 'clients.telephone',
  360. 'orders__total' => 'orders.total', 'orders__placed' => 'orders.placed'
  361. ];
  362. $this->assertEquals($expected, $select);
  363. }
  364. /**
  365. * Tests that default fields for associations are added to the select clause when
  366. * none is specified
  367. *
  368. * @return void
  369. */
  370. public function testContainToFieldsDefault()
  371. {
  372. $contains = ['clients' => ['orders']];
  373. $query = new Query($this->connection, $this->table);
  374. $query->select()->contain($contains)->sql();
  375. $select = $query->clause('select');
  376. $expected = [
  377. 'foo__id' => 'foo.id', 'clients__name' => 'clients.name',
  378. 'clients__id' => 'clients.id', 'clients__phone' => 'clients.phone',
  379. 'orders__id' => 'orders.id', 'orders__total' => 'orders.total',
  380. 'orders__placed' => 'orders.placed'
  381. ];
  382. $expected = $this->_quoteArray($expected);
  383. $this->assertEquals($expected, $select);
  384. $contains['clients']['fields'] = ['name'];
  385. $query = new Query($this->connection, $this->table);
  386. $query->select('foo.id')->contain($contains)->sql();
  387. $select = $query->clause('select');
  388. $expected = ['foo__id' => 'foo.id', 'clients__name' => 'clients.name'];
  389. $expected = $this->_quoteArray($expected);
  390. $this->assertEquals($expected, $select);
  391. $contains['clients']['fields'] = [];
  392. $contains['clients']['orders']['fields'] = false;
  393. $query = new Query($this->connection, $this->table);
  394. $query->select()->contain($contains)->sql();
  395. $select = $query->clause('select');
  396. $expected = [
  397. 'foo__id' => 'foo.id',
  398. 'clients__id' => 'clients.id',
  399. 'clients__name' => 'clients.name',
  400. 'clients__phone' => 'clients.phone',
  401. ];
  402. $expected = $this->_quoteArray($expected);
  403. $this->assertEquals($expected, $select);
  404. }
  405. /**
  406. * Tests that the path for getting to a deep association is materialized in an
  407. * array key
  408. *
  409. * @return void
  410. */
  411. public function testNormalizedPath()
  412. {
  413. $contains = [
  414. 'clients' => [
  415. 'orders' => [
  416. 'orderTypes',
  417. 'stuff' => ['stuffTypes']
  418. ],
  419. 'companies' => [
  420. 'categories'
  421. ]
  422. ]
  423. ];
  424. $query = $this->getMockBuilder('\Cake\ORM\Query')
  425. ->setMethods(['join'])
  426. ->setConstructorArgs([$this->connection, $this->table])
  427. ->getMock();
  428. $loader = new EagerLoader;
  429. $loader->contain($contains);
  430. $normalized = $loader->normalized($this->table);
  431. $this->assertEquals('clients', $normalized['clients']->aliasPath());
  432. $this->assertEquals('client', $normalized['clients']->propertyPath());
  433. $assocs = $normalized['clients']->associations();
  434. $this->assertEquals('clients.orders', $assocs['orders']->aliasPath());
  435. $this->assertEquals('client.order', $assocs['orders']->propertyPath());
  436. $assocs = $assocs['orders']->associations();
  437. $this->assertEquals('clients.orders.orderTypes', $assocs['orderTypes']->aliasPath());
  438. $this->assertEquals('client.order.order_type', $assocs['orderTypes']->propertyPath());
  439. $this->assertEquals('clients.orders.stuff', $assocs['stuff']->aliasPath());
  440. $this->assertEquals('client.order.stuff', $assocs['stuff']->propertyPath());
  441. $assocs = $assocs['stuff']->associations();
  442. $this->assertEquals(
  443. 'clients.orders.stuff.stuffTypes',
  444. $assocs['stuffTypes']->aliasPath()
  445. );
  446. $this->assertEquals(
  447. 'client.order.stuff.stuff_type',
  448. $assocs['stuffTypes']->propertyPath()
  449. );
  450. }
  451. /**
  452. * Test clearing containments but not matching joins.
  453. *
  454. * @return void
  455. */
  456. public function testClearContain()
  457. {
  458. $contains = [
  459. 'clients' => [
  460. 'orders' => [
  461. 'orderTypes',
  462. 'stuff' => ['stuffTypes']
  463. ],
  464. 'companies' => [
  465. 'categories'
  466. ]
  467. ]
  468. ];
  469. $loader = new EagerLoader();
  470. $loader->contain($contains);
  471. $loader->matching('clients.addresses');
  472. $this->assertNull($loader->clearContain());
  473. $result = $loader->normalized($this->table);
  474. $this->assertEquals([], $result);
  475. $this->assertArrayHasKey('clients', $loader->matching());
  476. }
  477. /**
  478. * Helper function sued to quoted both keys and values in an array in case
  479. * the test suite is running with auto quoting enabled
  480. *
  481. * @param array $elements
  482. * @return array
  483. */
  484. protected function _quoteArray($elements)
  485. {
  486. if ($this->connection->driver()->autoQuoting()) {
  487. $quoter = function ($e) {
  488. return $this->connection->driver()->quoteIdentifier($e);
  489. };
  490. return array_combine(
  491. array_map($quoter, array_keys($elements)),
  492. array_map($quoter, array_values($elements))
  493. );
  494. }
  495. return $elements;
  496. }
  497. /**
  498. * Asserts that matching('something') and setMatching('something') return consistent type.
  499. *
  500. * @return void
  501. */
  502. public function testSetMatchingReturnType()
  503. {
  504. $loader = new EagerLoader();
  505. $result = $loader->setMatching('clients');
  506. $this->assertInstanceOf(EagerLoader::class, $result);
  507. $this->assertArrayHasKey('clients', $loader->getMatching());
  508. $result = $loader->matching('customers');
  509. $this->assertArrayHasKey('customers', $result);
  510. $this->assertArrayHasKey('customers', $loader->getMatching());
  511. }
  512. }