TableSchemaTest.php 19 KB

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