TableSchemaTest.php 19 KB

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