TableSchemaTest.php 20 KB

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