EagerLoaderTest.php 15 KB

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