TableSchemaTest.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  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 $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. // Missing column
  381. [['columns' => ['not_there'], 'type' => TableSchema::INDEX_INDEX]],
  382. ];
  383. }
  384. /**
  385. * Test that an exception is raised when indexes
  386. * are added for fields that do not exist.
  387. *
  388. * @dataProvider addIndexErrorProvider
  389. */
  390. public function testAddIndexError(array $props): void
  391. {
  392. $this->expectException(DatabaseException::class);
  393. $table = new TableSchema('articles');
  394. $table->addColumn('author_id', 'integer');
  395. $table->addIndex('author_idx', $props);
  396. }
  397. /**
  398. * Test adding different kinds of indexes.
  399. */
  400. public function testAddIndexTypes(): void
  401. {
  402. $table = new TableSchema('articles');
  403. $table->addColumn('id', 'integer')
  404. ->addColumn('title', 'string')
  405. ->addColumn('author_id', 'integer');
  406. $table->addIndex('author_idx', [
  407. 'columns' => ['author_id'],
  408. 'type' => 'index',
  409. ])->addIndex('texty', [
  410. 'type' => 'fulltext',
  411. 'columns' => ['title'],
  412. ]);
  413. $this->assertEquals(
  414. ['author_idx', 'texty'],
  415. $table->indexes()
  416. );
  417. }
  418. /**
  419. * Test getting the primary key.
  420. */
  421. public function testPrimaryKey(): void
  422. {
  423. $table = new TableSchema('articles');
  424. $table->addColumn('id', 'integer')
  425. ->addColumn('title', 'string')
  426. ->addColumn('author_id', 'integer')
  427. ->addConstraint('author_idx', [
  428. 'columns' => ['author_id'],
  429. 'type' => 'unique',
  430. ])->addConstraint('primary', [
  431. 'type' => 'primary',
  432. 'columns' => ['id'],
  433. ]);
  434. $this->assertEquals(['id'], $table->getPrimaryKey());
  435. $table = new TableSchema('articles');
  436. $table->addColumn('id', 'integer')
  437. ->addColumn('title', 'string')
  438. ->addColumn('author_id', 'integer');
  439. $this->assertEquals([], $table->getPrimaryKey());
  440. }
  441. /**
  442. * Test the setOptions/getOptions methods.
  443. */
  444. public function testOptions(): void
  445. {
  446. $table = new TableSchema('articles');
  447. $options = [
  448. 'engine' => 'InnoDB',
  449. ];
  450. $return = $table->setOptions($options);
  451. $this->assertInstanceOf('Cake\Database\Schema\TableSchema', $return);
  452. $this->assertEquals($options, $table->getOptions());
  453. }
  454. /**
  455. * Add a basic foreign key constraint.
  456. */
  457. public function testAddConstraintForeignKey(): void
  458. {
  459. $table = new TableSchema('articles');
  460. $table->addColumn('author_id', 'integer')
  461. ->addConstraint('author_id_idx', [
  462. 'type' => TableSchema::CONSTRAINT_FOREIGN,
  463. 'columns' => ['author_id'],
  464. 'references' => ['authors', 'id'],
  465. 'update' => 'cascade',
  466. 'delete' => 'cascade',
  467. ]);
  468. $this->assertEquals(['author_id_idx'], $table->constraints());
  469. }
  470. /**
  471. * Test single column foreign keys constraint support
  472. */
  473. public function testConstraintForeignKey(): void
  474. {
  475. $table = $this->getTableLocator()->get('ArticlesTags');
  476. $compositeConstraint = $table->getSchema()->getConstraint('tag_id_fk');
  477. $expected = [
  478. 'type' => 'foreign',
  479. 'columns' => ['tag_id'],
  480. 'references' => ['tags', 'id'],
  481. 'update' => 'cascade',
  482. 'delete' => 'cascade',
  483. 'length' => [],
  484. ];
  485. $this->assertEquals($expected, $compositeConstraint);
  486. $expectedSubstring = 'CONSTRAINT <tag_id_fk> FOREIGN KEY \(<tag_id>\) REFERENCES <tags> \(<id>\)';
  487. $this->assertQuotedQuery($expectedSubstring, $table->getSchema()->createSql(ConnectionManager::get('test'))[0]);
  488. }
  489. /**
  490. * Test composite foreign keys support
  491. */
  492. public function testConstraintForeignKeyTwoColumns(): void
  493. {
  494. $this->getTableLocator()->clear();
  495. $table = $this->getTableLocator()->get('Orders');
  496. $connection = $table->getConnection();
  497. $this->skipIf(
  498. $connection->getDriver() instanceof Postgres,
  499. 'Constraints get dropped in postgres for some reason'
  500. );
  501. $compositeConstraint = $table->getSchema()->getConstraint('product_category_fk');
  502. $expected = [
  503. 'type' => 'foreign',
  504. 'columns' => [
  505. 'product_category',
  506. 'product_id',
  507. ],
  508. 'references' => [
  509. 'products',
  510. ['category', 'id'],
  511. ],
  512. 'update' => 'cascade',
  513. 'delete' => 'cascade',
  514. 'length' => [],
  515. ];
  516. $this->assertEquals($expected, $compositeConstraint);
  517. $expectedSubstring = 'CONSTRAINT <product_category_fk> FOREIGN KEY \(<product_category>, <product_id>\)' .
  518. ' REFERENCES <products> \(<category>, <id>\)';
  519. $this->assertQuotedQuery($expectedSubstring, $table->getSchema()->createSql(ConnectionManager::get('test'))[0]);
  520. }
  521. /**
  522. * Provider for exceptionally bad foreign key data.
  523. *
  524. * @return array
  525. */
  526. public static function badForeignKeyProvider(): array
  527. {
  528. return [
  529. 'references is bad' => [[
  530. 'type' => TableSchema::CONSTRAINT_FOREIGN,
  531. 'columns' => ['author_id'],
  532. 'references' => ['authors'],
  533. 'delete' => 'derp',
  534. ]],
  535. 'bad update value' => [[
  536. 'type' => TableSchema::CONSTRAINT_FOREIGN,
  537. 'columns' => ['author_id'],
  538. 'references' => ['authors', 'id'],
  539. 'update' => 'derp',
  540. ]],
  541. 'bad delete value' => [[
  542. 'type' => TableSchema::CONSTRAINT_FOREIGN,
  543. 'columns' => ['author_id'],
  544. 'references' => ['authors', 'id'],
  545. 'delete' => 'derp',
  546. ]],
  547. ];
  548. }
  549. /**
  550. * Add a foreign key constraint with bad data
  551. *
  552. * @dataProvider badForeignKeyProvider
  553. */
  554. public function testAddConstraintForeignKeyBadData(array $data): void
  555. {
  556. $this->expectException(DatabaseException::class);
  557. $table = new TableSchema('articles');
  558. $table->addColumn('author_id', 'integer')
  559. ->addConstraint('author_id_idx', $data);
  560. }
  561. /**
  562. * Tests the setTemporary() & isTemporary() method
  563. */
  564. public function testSetTemporary(): void
  565. {
  566. $table = new TableSchema('articles');
  567. $this->assertFalse($table->isTemporary());
  568. $this->assertSame($table, $table->setTemporary(true));
  569. $this->assertTrue($table->isTemporary());
  570. $table->setTemporary(false);
  571. $this->assertFalse($table->isTemporary());
  572. }
  573. /**
  574. * Assertion for comparing a regex pattern against a query having its identifiers
  575. * quoted. It accepts queries quoted with the characters `<` and `>`. If the third
  576. * parameter is set to true, it will alter the pattern to both accept quoted and
  577. * unquoted queries
  578. *
  579. * @param string $pattern
  580. * @param string $query the result to compare against
  581. * @param bool $optional
  582. */
  583. public function assertQuotedQuery($pattern, $query, $optional = false): void
  584. {
  585. if ($optional) {
  586. $optional = '?';
  587. }
  588. $pattern = str_replace('<', '[`"\[]' . $optional, $pattern);
  589. $pattern = str_replace('>', '[`"\]]' . $optional, $pattern);
  590. $this->assertMatchesRegularExpression('#' . $pattern . '#', $query);
  591. }
  592. }