TableSchemaTest.php 20 KB

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