TableSchemaTest.php 19 KB

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