TableTest.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  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\Database\Schema;
  16. use Cake\Database\Schema\Table;
  17. use Cake\Database\Type;
  18. use Cake\Datasource\ConnectionManager;
  19. use Cake\ORM\TableRegistry;
  20. use Cake\TestSuite\TestCase;
  21. /**
  22. * Mock class for testing baseType inheritance
  23. *
  24. */
  25. class FooType extends Type
  26. {
  27. public function getBaseType()
  28. {
  29. return 'integer';
  30. }
  31. }
  32. /**
  33. * Test case for Table
  34. */
  35. class TableTest extends TestCase
  36. {
  37. public $fixtures = [
  38. 'core.articles',
  39. 'core.tags',
  40. 'core.articles_tags',
  41. 'core.orders',
  42. 'core.products'
  43. ];
  44. protected $_map;
  45. public function setUp()
  46. {
  47. $this->_map = Type::map();
  48. parent::setUp();
  49. }
  50. public function tearDown()
  51. {
  52. TableRegistry::clear();
  53. Type::clear();
  54. Type::map($this->_map);
  55. parent::tearDown();
  56. }
  57. /**
  58. * Test construction with columns
  59. *
  60. * @return void
  61. */
  62. public function testConstructWithColumns()
  63. {
  64. $columns = [
  65. 'id' => [
  66. 'type' => 'integer',
  67. 'length' => 11,
  68. ],
  69. 'title' => [
  70. 'type' => 'string',
  71. 'length' => 255
  72. ]
  73. ];
  74. $table = new Table('articles', $columns);
  75. $this->assertEquals(['id', 'title'], $table->columns());
  76. }
  77. /**
  78. * Test adding columns.
  79. *
  80. * @return void
  81. */
  82. public function testAddColumn()
  83. {
  84. $table = new Table('articles');
  85. $result = $table->addColumn('title', [
  86. 'type' => 'string',
  87. 'length' => 25,
  88. 'null' => false
  89. ]);
  90. $this->assertSame($table, $result);
  91. $this->assertEquals(['title'], $table->columns());
  92. $result = $table->addColumn('body', 'text');
  93. $this->assertSame($table, $result);
  94. $this->assertEquals(['title', 'body'], $table->columns());
  95. }
  96. /**
  97. * Test isNullable method
  98. *
  99. * @return void
  100. */
  101. public function testIsNullable()
  102. {
  103. $table = new Table('articles');
  104. $table->addColumn('title', [
  105. 'type' => 'string',
  106. 'length' => 25,
  107. 'null' => false
  108. ])->addColumn('tagline', [
  109. 'type' => 'string',
  110. 'length' => 25,
  111. 'null' => true
  112. ]);
  113. $this->assertFalse($table->isNullable('title'));
  114. $this->assertTrue($table->isNullable('tagline'));
  115. $this->assertTrue($table->isNullable('missing'));
  116. }
  117. /**
  118. * Test columnType method
  119. *
  120. * @return void
  121. */
  122. public function testColumnType()
  123. {
  124. $table = new Table('articles');
  125. $table->addColumn('title', [
  126. 'type' => 'string',
  127. 'length' => 25,
  128. 'null' => false
  129. ]);
  130. $this->assertEquals('string', $table->columnType('title'));
  131. $this->assertNull($table->columnType('not there'));
  132. }
  133. /**
  134. * Test columnType setter method
  135. *
  136. * @return void
  137. */
  138. public function testColumnTypeSet()
  139. {
  140. $table = new Table('articles');
  141. $table->addColumn('title', [
  142. 'type' => 'string',
  143. 'length' => 25,
  144. 'null' => false
  145. ]);
  146. $this->assertEquals('string', $table->columnType('title'));
  147. $table->columnType('title', 'json');
  148. $this->assertEquals('json', $table->columnType('title'));
  149. }
  150. /**
  151. * Tests getting the baseType as configured when creating the column
  152. *
  153. * @return void
  154. */
  155. public function testBaseColumnType()
  156. {
  157. $table = new Table('articles');
  158. $table->addColumn('title', [
  159. 'type' => 'json',
  160. 'baseType' => 'text',
  161. 'length' => 25,
  162. 'null' => false
  163. ]);
  164. $this->assertEquals('json', $table->columnType('title'));
  165. $this->assertEquals('text', $table->baseColumnType('title'));
  166. }
  167. /**
  168. * Tests getting the base type as it is retuned by the Type class
  169. *
  170. * @return void
  171. */
  172. public function testBaseColumnTypeInherited()
  173. {
  174. Type::map('foo', __NAMESPACE__ . '\FooType');
  175. $table = new Table('articles');
  176. $table->addColumn('thing', [
  177. 'type' => 'foo',
  178. 'null' => false
  179. ]);
  180. $this->assertEquals('foo', $table->columnType('thing'));
  181. $this->assertEquals('integer', $table->baseColumnType('thing'));
  182. }
  183. /**
  184. * Attribute keys should be filtered and have defaults set.
  185. *
  186. * @return void
  187. */
  188. public function testAddColumnFiltersAttributes()
  189. {
  190. $table = new Table('articles');
  191. $table->addColumn('title', [
  192. 'type' => 'string'
  193. ]);
  194. $result = $table->column('title');
  195. $expected = [
  196. 'type' => 'string',
  197. 'length' => null,
  198. 'precision' => null,
  199. 'default' => null,
  200. 'null' => null,
  201. 'fixed' => null,
  202. 'comment' => null,
  203. 'collate' => null,
  204. ];
  205. $this->assertEquals($expected, $result);
  206. $table->addColumn('author_id', [
  207. 'type' => 'integer'
  208. ]);
  209. $result = $table->column('author_id');
  210. $expected = [
  211. 'type' => 'integer',
  212. 'length' => null,
  213. 'precision' => null,
  214. 'default' => null,
  215. 'null' => null,
  216. 'unsigned' => null,
  217. 'comment' => null,
  218. 'autoIncrement' => null,
  219. ];
  220. $this->assertEquals($expected, $result);
  221. $table->addColumn('amount', [
  222. 'type' => 'decimal'
  223. ]);
  224. $result = $table->column('amount');
  225. $expected = [
  226. 'type' => 'decimal',
  227. 'length' => null,
  228. 'precision' => null,
  229. 'default' => null,
  230. 'null' => null,
  231. 'unsigned' => null,
  232. 'comment' => null,
  233. ];
  234. $this->assertEquals($expected, $result);
  235. }
  236. /**
  237. * Test reading default values.
  238. *
  239. * @return void
  240. */
  241. public function testDefaultValues()
  242. {
  243. $table = new Table('articles');
  244. $table->addColumn('id', [
  245. 'type' => 'integer',
  246. 'default' => 0
  247. ])->addColumn('title', [
  248. 'type' => 'string',
  249. 'default' => 'A title'
  250. ])->addColumn('name', [
  251. 'type' => 'string',
  252. 'null' => false,
  253. 'default' => null,
  254. ])->addColumn('body', [
  255. 'type' => 'text',
  256. 'null' => true,
  257. 'default' => null,
  258. ]);
  259. $result = $table->defaultValues();
  260. $expected = [
  261. 'id' => 0,
  262. 'title' => 'A title',
  263. 'body' => null
  264. ];
  265. $this->assertEquals($expected, $result);
  266. }
  267. /**
  268. * Test adding an constraint.
  269. * >
  270. * @return void
  271. */
  272. public function testAddConstraint()
  273. {
  274. $table = new Table('articles');
  275. $table->addColumn('id', [
  276. 'type' => 'integer'
  277. ]);
  278. $result = $table->addConstraint('primary', [
  279. 'type' => 'primary',
  280. 'columns' => ['id']
  281. ]);
  282. $this->assertSame($result, $table);
  283. $this->assertEquals(['primary'], $table->constraints());
  284. }
  285. /**
  286. * Test adding an constraint with an overlapping unique index
  287. * >
  288. * @return void
  289. */
  290. public function testAddConstraintOverwriteUniqueIndex()
  291. {
  292. $table = new Table('articles');
  293. $table->addColumn('project_id', [
  294. 'type' => 'integer',
  295. 'default' => null,
  296. 'limit' => 11,
  297. 'null' => false,
  298. ])->addColumn('id', [
  299. 'type' => 'integer',
  300. 'autoIncrement' => true,
  301. 'limit' => 11
  302. ])->addColumn('user_id', [
  303. 'type' => 'integer',
  304. 'default' => null,
  305. 'limit' => 11,
  306. 'null' => false,
  307. ])->addConstraint('users_idx', [
  308. 'type' => 'unique',
  309. 'columns' => ['project_id', 'user_id']
  310. ])->addConstraint('users_idx', [
  311. 'type' => 'foreign',
  312. 'references' => ['users', 'project_id', 'id'],
  313. 'columns' => ['project_id', 'user_id']
  314. ]);
  315. $this->assertEquals(['users_idx'], $table->constraints());
  316. }
  317. /**
  318. * Dataprovider for invalid addConstraint calls.
  319. *
  320. * @return array
  321. */
  322. public static function addConstaintErrorProvider()
  323. {
  324. return [
  325. // No properties
  326. [[]],
  327. // Empty columns
  328. [['columns' => '', 'type' => Table::CONSTRAINT_UNIQUE]],
  329. [['columns' => [], 'type' => Table::CONSTRAINT_UNIQUE]],
  330. // Missing column
  331. [['columns' => ['derp'], 'type' => Table::CONSTRAINT_UNIQUE]],
  332. // Invalid type
  333. [['columns' => 'author_id', 'type' => 'derp']],
  334. ];
  335. }
  336. /**
  337. * Test that an exception is raised when constraints
  338. * are added for fields that do not exist.
  339. *
  340. * @dataProvider addConstaintErrorProvider
  341. * @expectedException \Cake\Database\Exception
  342. * @return void
  343. */
  344. public function testAddConstraintError($props)
  345. {
  346. $table = new Table('articles');
  347. $table->addColumn('author_id', 'integer');
  348. $table->addConstraint('author_idx', $props);
  349. }
  350. /**
  351. * Test adding an index.
  352. *
  353. * @return void
  354. */
  355. public function testAddIndex()
  356. {
  357. $table = new Table('articles');
  358. $table->addColumn('title', [
  359. 'type' => 'string'
  360. ]);
  361. $result = $table->addIndex('faster', [
  362. 'type' => 'index',
  363. 'columns' => ['title']
  364. ]);
  365. $this->assertSame($result, $table);
  366. $this->assertEquals(['faster'], $table->indexes());
  367. }
  368. /**
  369. * Dataprovider for invalid addIndex calls
  370. *
  371. * @return array
  372. */
  373. public static function addIndexErrorProvider()
  374. {
  375. return [
  376. // Empty
  377. [[]],
  378. // Invalid type
  379. [['columns' => 'author_id', 'type' => 'derp']],
  380. // No columns
  381. [['columns' => ''], 'type' => Table::INDEX_INDEX],
  382. [['columns' => [], 'type' => Table::INDEX_INDEX]],
  383. // Missing column
  384. [['columns' => ['not_there'], 'type' => Table::INDEX_INDEX]],
  385. ];
  386. }
  387. /**
  388. * Test that an exception is raised when indexes
  389. * are added for fields that do not exist.
  390. *
  391. * @dataProvider addIndexErrorProvider
  392. * @expectedException \Cake\Database\Exception
  393. * @return void
  394. */
  395. public function testAddIndexError($props)
  396. {
  397. $table = new Table('articles');
  398. $table->addColumn('author_id', 'integer');
  399. $table->addIndex('author_idx', $props);
  400. }
  401. /**
  402. * Test adding different kinds of indexes.
  403. *
  404. * @return void
  405. */
  406. public function testAddIndexTypes()
  407. {
  408. $table = new Table('articles');
  409. $table->addColumn('id', 'integer')
  410. ->addColumn('title', 'string')
  411. ->addColumn('author_id', 'integer');
  412. $table->addIndex('author_idx', [
  413. 'columns' => ['author_id'],
  414. 'type' => 'index'
  415. ])->addIndex('texty', [
  416. 'type' => 'fulltext',
  417. 'columns' => ['title']
  418. ]);
  419. $this->assertEquals(
  420. ['author_idx', 'texty'],
  421. $table->indexes()
  422. );
  423. }
  424. /**
  425. * Test getting the primary key.
  426. *
  427. * @return void
  428. */
  429. public function testPrimaryKey()
  430. {
  431. $table = new Table('articles');
  432. $table->addColumn('id', 'integer')
  433. ->addColumn('title', 'string')
  434. ->addColumn('author_id', 'integer')
  435. ->addConstraint('author_idx', [
  436. 'columns' => ['author_id'],
  437. 'type' => 'unique'
  438. ])->addConstraint('primary', [
  439. 'type' => 'primary',
  440. 'columns' => ['id']
  441. ]);
  442. $this->assertEquals(['id'], $table->primaryKey());
  443. $table = new Table('articles');
  444. $table->addColumn('id', 'integer')
  445. ->addColumn('title', 'string')
  446. ->addColumn('author_id', 'integer');
  447. $this->assertEquals([], $table->primaryKey());
  448. }
  449. /**
  450. * Test the options method.
  451. *
  452. * @return void
  453. */
  454. public function testOptions()
  455. {
  456. $table = new Table('articles');
  457. $options = [
  458. 'engine' => 'InnoDB'
  459. ];
  460. $return = $table->options($options);
  461. $this->assertInstanceOf('Cake\Database\Schema\Table', $return);
  462. $this->assertEquals($options, $table->options());
  463. }
  464. /**
  465. * Add a basic foreign key constraint.
  466. *
  467. * @return void
  468. */
  469. public function testAddConstraintForeignKey()
  470. {
  471. $table = new Table('articles');
  472. $table->addColumn('author_id', 'integer')
  473. ->addConstraint('author_id_idx', [
  474. 'type' => Table::CONSTRAINT_FOREIGN,
  475. 'columns' => ['author_id'],
  476. 'references' => ['authors', 'id'],
  477. 'update' => 'cascade',
  478. 'delete' => 'cascade',
  479. ]);
  480. $this->assertEquals(['author_id_idx'], $table->constraints());
  481. }
  482. /**
  483. * Test single column foreign keys constraint support
  484. *
  485. * @return void
  486. */
  487. public function testConstraintForeignKey()
  488. {
  489. $table = TableRegistry::get('ArticlesTags');
  490. $compositeConstraint = $table->schema()->constraint('tag_id_fk');
  491. $expected = [
  492. 'type' => 'foreign',
  493. 'columns' => ['tag_id'],
  494. 'references' => ['tags', 'id'],
  495. 'update' => 'cascade',
  496. 'delete' => 'cascade',
  497. 'length' => []
  498. ];
  499. $this->assertEquals($expected, $compositeConstraint);
  500. $expectedSubstring = 'CONSTRAINT <tag_id_fk> FOREIGN KEY \(<tag_id>\) REFERENCES <tags> \(<id>\)';
  501. $this->assertQuotedQuery($expectedSubstring, $table->schema()->createSql(ConnectionManager::get('test'))[0]);
  502. }
  503. /**
  504. * Test composite foreign keys support
  505. *
  506. * @return void
  507. */
  508. public function testConstraintForeignKeyTwoColumns()
  509. {
  510. $table = TableRegistry::get('Orders');
  511. $compositeConstraint = $table->schema()->constraint('product_category_fk');
  512. $expected = [
  513. 'type' => 'foreign',
  514. 'columns' => [
  515. 'product_category',
  516. 'product_id'
  517. ],
  518. 'references' => [
  519. 'products',
  520. ['category', 'id']
  521. ],
  522. 'update' => 'cascade',
  523. 'delete' => 'cascade',
  524. 'length' => []
  525. ];
  526. $this->assertEquals($expected, $compositeConstraint);
  527. $expectedSubstring = 'CONSTRAINT <product_category_fk> FOREIGN KEY \(<product_category>, <product_id>\)' .
  528. ' REFERENCES <products> \(<category>, <id>\)';
  529. $this->assertQuotedQuery($expectedSubstring, $table->schema()->createSql(ConnectionManager::get('test'))[0]);
  530. }
  531. /**
  532. * Provider for exceptionally bad foreign key data.
  533. *
  534. * @return array
  535. */
  536. public static function badForeignKeyProvider()
  537. {
  538. return [
  539. 'references is bad' => [[
  540. 'type' => Table::CONSTRAINT_FOREIGN,
  541. 'columns' => ['author_id'],
  542. 'references' => ['authors'],
  543. 'delete' => 'derp',
  544. ]],
  545. 'bad update value' => [[
  546. 'type' => Table::CONSTRAINT_FOREIGN,
  547. 'columns' => ['author_id'],
  548. 'references' => ['authors', 'id'],
  549. 'update' => 'derp',
  550. ]],
  551. 'bad delete value' => [[
  552. 'type' => Table::CONSTRAINT_FOREIGN,
  553. 'columns' => ['author_id'],
  554. 'references' => ['authors', 'id'],
  555. 'delete' => 'derp',
  556. ]],
  557. ];
  558. }
  559. /**
  560. * Add a foreign key constraint with bad data
  561. *
  562. * @dataProvider badForeignKeyProvider
  563. * @expectedException \Cake\Database\Exception
  564. * @return void
  565. */
  566. public function testAddConstraintForeignKeyBadData($data)
  567. {
  568. $table = new Table('articles');
  569. $table->addColumn('author_id', 'integer')
  570. ->addConstraint('author_id_idx', $data);
  571. }
  572. /**
  573. * Tests the temporary() method
  574. *
  575. * @return void
  576. */
  577. public function testTemporary()
  578. {
  579. $table = new Table('articles');
  580. $this->assertFalse($table->temporary());
  581. $this->assertSame($table, $table->temporary(true));
  582. $this->assertTrue($table->temporary());
  583. $table->temporary(false);
  584. $this->assertFalse($table->temporary());
  585. }
  586. /**
  587. * Assertion for comparing a regex pattern against a query having its identifiers
  588. * quoted. It accepts queries quoted with the characters `<` and `>`. If the third
  589. * parameter is set to true, it will alter the pattern to both accept quoted and
  590. * unquoted queries
  591. *
  592. * @param string $pattern
  593. * @param string $query the result to compare against
  594. * @param bool $optional
  595. * @return void
  596. */
  597. public function assertQuotedQuery($pattern, $query, $optional = false)
  598. {
  599. if ($optional) {
  600. $optional = '?';
  601. }
  602. $pattern = str_replace('<', '[`"\[]' . $optional, $pattern);
  603. $pattern = str_replace('>', '[`"\]]' . $optional, $pattern);
  604. $this->assertRegExp('#' . $pattern . '#', $query);
  605. }
  606. }