TableTest.php 19 KB

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