TableSchemaTest.php 19 KB

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