TableSchemaTest.php 20 KB

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