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. * @return void
  300. */
  301. public function testAddConstraint()
  302. {
  303. $table = new TableSchema('articles');
  304. $table->addColumn('id', [
  305. 'type' => 'integer',
  306. ]);
  307. $result = $table->addConstraint('primary', [
  308. 'type' => 'primary',
  309. 'columns' => ['id'],
  310. ]);
  311. $this->assertSame($result, $table);
  312. $this->assertEquals(['primary'], $table->constraints());
  313. }
  314. /**
  315. * Test adding an constraint with an overlapping unique index
  316. * >
  317. * @return void
  318. */
  319. public function testAddConstraintOverwriteUniqueIndex()
  320. {
  321. $table = new TableSchema('articles');
  322. $table->addColumn('project_id', [
  323. 'type' => 'integer',
  324. 'default' => null,
  325. 'limit' => 11,
  326. 'null' => false,
  327. ])->addColumn('id', [
  328. 'type' => 'integer',
  329. 'autoIncrement' => true,
  330. 'limit' => 11,
  331. ])->addColumn('user_id', [
  332. 'type' => 'integer',
  333. 'default' => null,
  334. 'limit' => 11,
  335. 'null' => false,
  336. ])->addConstraint('users_idx', [
  337. 'type' => 'unique',
  338. 'columns' => ['project_id', 'user_id'],
  339. ])->addConstraint('users_idx', [
  340. 'type' => 'foreign',
  341. 'references' => ['users', 'project_id', 'id'],
  342. 'columns' => ['project_id', 'user_id'],
  343. ]);
  344. $this->assertEquals(['users_idx'], $table->constraints());
  345. }
  346. /**
  347. * Dataprovider for invalid addConstraint calls.
  348. *
  349. * @return array
  350. */
  351. public static function addConstraintErrorProvider()
  352. {
  353. return [
  354. // No properties
  355. [[]],
  356. // Empty columns
  357. [['columns' => '', 'type' => TableSchema::CONSTRAINT_UNIQUE]],
  358. [['columns' => [], 'type' => TableSchema::CONSTRAINT_UNIQUE]],
  359. // Missing column
  360. [['columns' => ['derp'], 'type' => TableSchema::CONSTRAINT_UNIQUE]],
  361. // Invalid type
  362. [['columns' => 'author_id', 'type' => 'derp']],
  363. ];
  364. }
  365. /**
  366. * Test that an exception is raised when constraints
  367. * are added for fields that do not exist.
  368. *
  369. * @dataProvider addConstraintErrorProvider
  370. * @return void
  371. */
  372. public function testAddConstraintError($props)
  373. {
  374. $this->expectException(\Cake\Database\Exception::class);
  375. $table = new TableSchema('articles');
  376. $table->addColumn('author_id', 'integer');
  377. $table->addConstraint('author_idx', $props);
  378. }
  379. /**
  380. * Test adding an index.
  381. *
  382. * @return void
  383. */
  384. public function testAddIndex()
  385. {
  386. $table = new TableSchema('articles');
  387. $table->addColumn('title', [
  388. 'type' => 'string',
  389. ]);
  390. $result = $table->addIndex('faster', [
  391. 'type' => 'index',
  392. 'columns' => ['title'],
  393. ]);
  394. $this->assertSame($result, $table);
  395. $this->assertEquals(['faster'], $table->indexes());
  396. }
  397. /**
  398. * Dataprovider for invalid addIndex calls
  399. *
  400. * @return array
  401. */
  402. public static function addIndexErrorProvider()
  403. {
  404. return [
  405. // Empty
  406. [[]],
  407. // Invalid type
  408. [['columns' => 'author_id', 'type' => 'derp']],
  409. // No columns
  410. [['columns' => ''], 'type' => TableSchema::INDEX_INDEX],
  411. [['columns' => [], 'type' => TableSchema::INDEX_INDEX]],
  412. // Missing column
  413. [['columns' => ['not_there'], 'type' => TableSchema::INDEX_INDEX]],
  414. ];
  415. }
  416. /**
  417. * Test that an exception is raised when indexes
  418. * are added for fields that do not exist.
  419. *
  420. * @dataProvider addIndexErrorProvider
  421. * @return void
  422. */
  423. public function testAddIndexError($props)
  424. {
  425. $this->expectException(\Cake\Database\Exception::class);
  426. $table = new TableSchema('articles');
  427. $table->addColumn('author_id', 'integer');
  428. $table->addIndex('author_idx', $props);
  429. }
  430. /**
  431. * Test adding different kinds of indexes.
  432. *
  433. * @return void
  434. */
  435. public function testAddIndexTypes()
  436. {
  437. $table = new TableSchema('articles');
  438. $table->addColumn('id', 'integer')
  439. ->addColumn('title', 'string')
  440. ->addColumn('author_id', 'integer');
  441. $table->addIndex('author_idx', [
  442. 'columns' => ['author_id'],
  443. 'type' => 'index',
  444. ])->addIndex('texty', [
  445. 'type' => 'fulltext',
  446. 'columns' => ['title'],
  447. ]);
  448. $this->assertEquals(
  449. ['author_idx', 'texty'],
  450. $table->indexes()
  451. );
  452. }
  453. /**
  454. * Test getting the primary key.
  455. *
  456. * @return void
  457. */
  458. public function testPrimaryKey()
  459. {
  460. $table = new TableSchema('articles');
  461. $table->addColumn('id', 'integer')
  462. ->addColumn('title', 'string')
  463. ->addColumn('author_id', 'integer')
  464. ->addConstraint('author_idx', [
  465. 'columns' => ['author_id'],
  466. 'type' => 'unique',
  467. ])->addConstraint('primary', [
  468. 'type' => 'primary',
  469. 'columns' => ['id'],
  470. ]);
  471. $this->assertEquals(['id'], $table->primaryKey());
  472. $table = new TableSchema('articles');
  473. $table->addColumn('id', 'integer')
  474. ->addColumn('title', 'string')
  475. ->addColumn('author_id', 'integer');
  476. $this->assertEquals([], $table->primaryKey());
  477. }
  478. /**
  479. * Test the setOptions/getOptions methods.
  480. *
  481. * @return void
  482. */
  483. public function testOptions()
  484. {
  485. $table = new TableSchema('articles');
  486. $options = [
  487. 'engine' => 'InnoDB',
  488. ];
  489. $return = $table->setOptions($options);
  490. $this->assertInstanceOf('Cake\Database\Schema\TableSchema', $return);
  491. $this->assertEquals($options, $table->getOptions());
  492. }
  493. /**
  494. * Test the options method.
  495. *
  496. * @group deprecated
  497. * @return void
  498. */
  499. public function testOptionsDeprecated()
  500. {
  501. $table = new TableSchema('articles');
  502. $options = [
  503. 'engine' => 'InnoDB',
  504. ];
  505. $this->deprecated(function () use ($table, $options) {
  506. $return = $table->options($options);
  507. $this->assertInstanceOf('Cake\Database\Schema\TableSchema', $return);
  508. $this->assertEquals($options, $table->options());
  509. });
  510. }
  511. /**
  512. * Add a basic foreign key constraint.
  513. *
  514. * @return void
  515. */
  516. public function testAddConstraintForeignKey()
  517. {
  518. $table = new TableSchema('articles');
  519. $table->addColumn('author_id', 'integer')
  520. ->addConstraint('author_id_idx', [
  521. 'type' => TableSchema::CONSTRAINT_FOREIGN,
  522. 'columns' => ['author_id'],
  523. 'references' => ['authors', 'id'],
  524. 'update' => 'cascade',
  525. 'delete' => 'cascade',
  526. ]);
  527. $this->assertEquals(['author_id_idx'], $table->constraints());
  528. }
  529. /**
  530. * Test single column foreign keys constraint support
  531. *
  532. * @return void
  533. */
  534. public function testConstraintForeignKey()
  535. {
  536. $table = $this->getTableLocator()->get('ArticlesTags');
  537. $compositeConstraint = $table->getSchema()->getConstraint('tag_id_fk');
  538. $expected = [
  539. 'type' => 'foreign',
  540. 'columns' => ['tag_id'],
  541. 'references' => ['tags', 'id'],
  542. 'update' => 'cascade',
  543. 'delete' => 'cascade',
  544. 'length' => [],
  545. ];
  546. $this->assertEquals($expected, $compositeConstraint);
  547. $expectedSubstring = 'CONSTRAINT <tag_id_fk> FOREIGN KEY \(<tag_id>\) REFERENCES <tags> \(<id>\)';
  548. $this->assertQuotedQuery($expectedSubstring, $table->getSchema()->createSql(ConnectionManager::get('test'))[0]);
  549. }
  550. /**
  551. * Test composite foreign keys support
  552. *
  553. * @return void
  554. */
  555. public function testConstraintForeignKeyTwoColumns()
  556. {
  557. $table = $this->getTableLocator()->get('Orders');
  558. $compositeConstraint = $table->getSchema()->getConstraint('product_category_fk');
  559. $expected = [
  560. 'type' => 'foreign',
  561. 'columns' => [
  562. 'product_category',
  563. 'product_id',
  564. ],
  565. 'references' => [
  566. 'products',
  567. ['category', 'id'],
  568. ],
  569. 'update' => 'cascade',
  570. 'delete' => 'cascade',
  571. 'length' => [],
  572. ];
  573. $this->assertEquals($expected, $compositeConstraint);
  574. $expectedSubstring = 'CONSTRAINT <product_category_fk> FOREIGN KEY \(<product_category>, <product_id>\)' .
  575. ' REFERENCES <products> \(<category>, <id>\)';
  576. $this->assertQuotedQuery($expectedSubstring, $table->getSchema()->createSql(ConnectionManager::get('test'))[0]);
  577. }
  578. /**
  579. * Provider for exceptionally bad foreign key data.
  580. *
  581. * @return array
  582. */
  583. public static function badForeignKeyProvider()
  584. {
  585. return [
  586. 'references is bad' => [[
  587. 'type' => TableSchema::CONSTRAINT_FOREIGN,
  588. 'columns' => ['author_id'],
  589. 'references' => ['authors'],
  590. 'delete' => 'derp',
  591. ]],
  592. 'bad update value' => [[
  593. 'type' => TableSchema::CONSTRAINT_FOREIGN,
  594. 'columns' => ['author_id'],
  595. 'references' => ['authors', 'id'],
  596. 'update' => 'derp',
  597. ]],
  598. 'bad delete value' => [[
  599. 'type' => TableSchema::CONSTRAINT_FOREIGN,
  600. 'columns' => ['author_id'],
  601. 'references' => ['authors', 'id'],
  602. 'delete' => 'derp',
  603. ]],
  604. ];
  605. }
  606. /**
  607. * Add a foreign key constraint with bad data
  608. *
  609. * @dataProvider badForeignKeyProvider
  610. * @return void
  611. */
  612. public function testAddConstraintForeignKeyBadData($data)
  613. {
  614. $this->expectException(\Cake\Database\Exception::class);
  615. $table = new TableSchema('articles');
  616. $table->addColumn('author_id', 'integer')
  617. ->addConstraint('author_id_idx', $data);
  618. }
  619. /**
  620. * Tests the temporary() method
  621. *
  622. * @return void
  623. */
  624. public function testTemporary()
  625. {
  626. $this->deprecated(function () {
  627. $table = new TableSchema('articles');
  628. $this->assertFalse($table->temporary());
  629. $this->assertSame($table, $table->temporary(true));
  630. $this->assertTrue($table->temporary());
  631. $table->temporary(false);
  632. $this->assertFalse($table->temporary());
  633. });
  634. }
  635. /**
  636. * Tests the setTemporary() & isTemporary() method
  637. *
  638. * @return void
  639. */
  640. public function testSetTemporary()
  641. {
  642. $table = new TableSchema('articles');
  643. $this->assertFalse($table->isTemporary());
  644. $this->assertSame($table, $table->setTemporary(true));
  645. $this->assertTrue($table->isTemporary());
  646. $table->setTemporary(false);
  647. $this->assertFalse($table->isTemporary());
  648. }
  649. /**
  650. * Assertion for comparing a regex pattern against a query having its identifiers
  651. * quoted. It accepts queries quoted with the characters `<` and `>`. If the third
  652. * parameter is set to true, it will alter the pattern to both accept quoted and
  653. * unquoted queries
  654. *
  655. * @param string $pattern
  656. * @param string $query the result to compare against
  657. * @param bool $optional
  658. * @return void
  659. */
  660. public function assertQuotedQuery($pattern, $query, $optional = false)
  661. {
  662. if ($optional) {
  663. $optional = '?';
  664. }
  665. $pattern = str_replace('<', '[`"\[]' . $optional, $pattern);
  666. $pattern = str_replace('>', '[`"\]]' . $optional, $pattern);
  667. $this->assertRegExp('#' . $pattern . '#', $query);
  668. }
  669. }