TableSchemaTest.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  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\Schema\TableSchema;
  18. use Cake\Database\TypeFactory;
  19. use Cake\Datasource\ConnectionManager;
  20. use Cake\TestSuite\TestCase;
  21. use TestApp\Database\Type\IntType;
  22. /**
  23. * Test case for Table
  24. */
  25. class TableSchemaTest extends TestCase
  26. {
  27. public $fixtures = [
  28. 'core.Articles',
  29. 'core.Tags',
  30. 'core.ArticlesTags',
  31. 'core.Orders',
  32. 'core.Products',
  33. ];
  34. protected $_map;
  35. public function setUp()
  36. {
  37. $this->_map = TypeFactory::getMap();
  38. parent::setUp();
  39. }
  40. public function tearDown()
  41. {
  42. $this->getTableLocator()->clear();
  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->assertEquals('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->assertEquals('string', $table->getColumnType('title'));
  169. $table->setColumnType('title', 'json');
  170. $this->assertEquals('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->assertEquals('json', $table->getColumnType('title'));
  187. $this->assertEquals('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->assertEquals('int', $table->getColumnType('thing'));
  203. $this->assertEquals('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. 'fixed' => null,
  224. 'comment' => null,
  225. 'collate' => null,
  226. ];
  227. $this->assertEquals($expected, $result);
  228. $table->addColumn('author_id', [
  229. 'type' => 'integer',
  230. ]);
  231. $result = $table->getColumn('author_id');
  232. $expected = [
  233. 'type' => 'integer',
  234. 'length' => null,
  235. 'precision' => null,
  236. 'default' => null,
  237. 'null' => null,
  238. 'unsigned' => null,
  239. 'comment' => null,
  240. 'autoIncrement' => null,
  241. ];
  242. $this->assertEquals($expected, $result);
  243. $table->addColumn('amount', [
  244. 'type' => 'decimal',
  245. ]);
  246. $result = $table->getColumn('amount');
  247. $expected = [
  248. 'type' => 'decimal',
  249. 'length' => null,
  250. 'precision' => null,
  251. 'default' => null,
  252. 'null' => null,
  253. 'unsigned' => null,
  254. 'comment' => null,
  255. ];
  256. $this->assertEquals($expected, $result);
  257. }
  258. /**
  259. * Test reading default values.
  260. *
  261. * @return void
  262. */
  263. public function testDefaultValues()
  264. {
  265. $table = new TableSchema('articles');
  266. $table->addColumn('id', [
  267. 'type' => 'integer',
  268. 'default' => 0,
  269. ])->addColumn('title', [
  270. 'type' => 'string',
  271. 'default' => 'A title',
  272. ])->addColumn('name', [
  273. 'type' => 'string',
  274. 'null' => false,
  275. 'default' => null,
  276. ])->addColumn('body', [
  277. 'type' => 'text',
  278. 'null' => true,
  279. 'default' => null,
  280. ]);
  281. $result = $table->defaultValues();
  282. $expected = [
  283. 'id' => 0,
  284. 'title' => 'A title',
  285. 'body' => null,
  286. ];
  287. $this->assertEquals($expected, $result);
  288. }
  289. /**
  290. * Test adding an constraint.
  291. * >
  292. * @return void
  293. */
  294. public function testAddConstraint()
  295. {
  296. $table = new TableSchema('articles');
  297. $table->addColumn('id', [
  298. 'type' => 'integer',
  299. ]);
  300. $result = $table->addConstraint('primary', [
  301. 'type' => 'primary',
  302. 'columns' => ['id'],
  303. ]);
  304. $this->assertSame($result, $table);
  305. $this->assertEquals(['primary'], $table->constraints());
  306. }
  307. /**
  308. * Test adding an constraint with an overlapping unique index
  309. * >
  310. * @return void
  311. */
  312. public function testAddConstraintOverwriteUniqueIndex()
  313. {
  314. $table = new TableSchema('articles');
  315. $table->addColumn('project_id', [
  316. 'type' => 'integer',
  317. 'default' => null,
  318. 'limit' => 11,
  319. 'null' => false,
  320. ])->addColumn('id', [
  321. 'type' => 'integer',
  322. 'autoIncrement' => true,
  323. 'limit' => 11,
  324. ])->addColumn('user_id', [
  325. 'type' => 'integer',
  326. 'default' => null,
  327. 'limit' => 11,
  328. 'null' => false,
  329. ])->addConstraint('users_idx', [
  330. 'type' => 'unique',
  331. 'columns' => ['project_id', 'user_id'],
  332. ])->addConstraint('users_idx', [
  333. 'type' => 'foreign',
  334. 'references' => ['users', 'project_id', 'id'],
  335. 'columns' => ['project_id', 'user_id'],
  336. ]);
  337. $this->assertEquals(['users_idx'], $table->constraints());
  338. }
  339. /**
  340. * Dataprovider for invalid addConstraint calls.
  341. *
  342. * @return array
  343. */
  344. public static function addConstraintErrorProvider()
  345. {
  346. return [
  347. // No properties
  348. [[]],
  349. // Empty columns
  350. [['columns' => '', 'type' => TableSchema::CONSTRAINT_UNIQUE]],
  351. [['columns' => [], 'type' => TableSchema::CONSTRAINT_UNIQUE]],
  352. // Missing column
  353. [['columns' => ['derp'], 'type' => TableSchema::CONSTRAINT_UNIQUE]],
  354. // Invalid type
  355. [['columns' => 'author_id', 'type' => 'derp']],
  356. ];
  357. }
  358. /**
  359. * Test that an exception is raised when constraints
  360. * are added for fields that do not exist.
  361. *
  362. * @dataProvider addConstraintErrorProvider
  363. * @return void
  364. */
  365. public function testAddConstraintError($props)
  366. {
  367. $this->expectException(\Cake\Database\Exception::class);
  368. $table = new TableSchema('articles');
  369. $table->addColumn('author_id', 'integer');
  370. $table->addConstraint('author_idx', $props);
  371. }
  372. /**
  373. * Test adding an index.
  374. *
  375. * @return void
  376. */
  377. public function testAddIndex()
  378. {
  379. $table = new TableSchema('articles');
  380. $table->addColumn('title', [
  381. 'type' => 'string',
  382. ]);
  383. $result = $table->addIndex('faster', [
  384. 'type' => 'index',
  385. 'columns' => ['title'],
  386. ]);
  387. $this->assertSame($result, $table);
  388. $this->assertEquals(['faster'], $table->indexes());
  389. }
  390. /**
  391. * Dataprovider for invalid addIndex calls
  392. *
  393. * @return array
  394. */
  395. public static function addIndexErrorProvider()
  396. {
  397. return [
  398. // Empty
  399. [[]],
  400. // Invalid type
  401. [['columns' => 'author_id', 'type' => 'derp']],
  402. // No columns
  403. [['columns' => ''], 'type' => TableSchema::INDEX_INDEX],
  404. [['columns' => [], 'type' => TableSchema::INDEX_INDEX]],
  405. // Missing column
  406. [['columns' => ['not_there'], 'type' => TableSchema::INDEX_INDEX]],
  407. ];
  408. }
  409. /**
  410. * Test that an exception is raised when indexes
  411. * are added for fields that do not exist.
  412. *
  413. * @dataProvider addIndexErrorProvider
  414. * @return void
  415. */
  416. public function testAddIndexError($props)
  417. {
  418. $this->expectException(\Cake\Database\Exception::class);
  419. $table = new TableSchema('articles');
  420. $table->addColumn('author_id', 'integer');
  421. $table->addIndex('author_idx', $props);
  422. }
  423. /**
  424. * Test adding different kinds of indexes.
  425. *
  426. * @return void
  427. */
  428. public function testAddIndexTypes()
  429. {
  430. $table = new TableSchema('articles');
  431. $table->addColumn('id', 'integer')
  432. ->addColumn('title', 'string')
  433. ->addColumn('author_id', 'integer');
  434. $table->addIndex('author_idx', [
  435. 'columns' => ['author_id'],
  436. 'type' => 'index',
  437. ])->addIndex('texty', [
  438. 'type' => 'fulltext',
  439. 'columns' => ['title'],
  440. ]);
  441. $this->assertEquals(
  442. ['author_idx', 'texty'],
  443. $table->indexes()
  444. );
  445. }
  446. /**
  447. * Test getting the primary key.
  448. *
  449. * @return void
  450. */
  451. public function testPrimaryKey()
  452. {
  453. $table = new TableSchema('articles');
  454. $table->addColumn('id', 'integer')
  455. ->addColumn('title', 'string')
  456. ->addColumn('author_id', 'integer')
  457. ->addConstraint('author_idx', [
  458. 'columns' => ['author_id'],
  459. 'type' => 'unique',
  460. ])->addConstraint('primary', [
  461. 'type' => 'primary',
  462. 'columns' => ['id'],
  463. ]);
  464. $this->assertEquals(['id'], $table->primaryKey());
  465. $table = new TableSchema('articles');
  466. $table->addColumn('id', 'integer')
  467. ->addColumn('title', 'string')
  468. ->addColumn('author_id', 'integer');
  469. $this->assertEquals([], $table->primaryKey());
  470. }
  471. /**
  472. * Test the setOptions/getOptions methods.
  473. *
  474. * @return void
  475. */
  476. public function testOptions()
  477. {
  478. $table = new TableSchema('articles');
  479. $options = [
  480. 'engine' => 'InnoDB',
  481. ];
  482. $return = $table->setOptions($options);
  483. $this->assertInstanceOf('Cake\Database\Schema\TableSchema', $return);
  484. $this->assertEquals($options, $table->getOptions());
  485. }
  486. /**
  487. * Add a basic foreign key constraint.
  488. *
  489. * @return void
  490. */
  491. public function testAddConstraintForeignKey()
  492. {
  493. $table = new TableSchema('articles');
  494. $table->addColumn('author_id', 'integer')
  495. ->addConstraint('author_id_idx', [
  496. 'type' => TableSchema::CONSTRAINT_FOREIGN,
  497. 'columns' => ['author_id'],
  498. 'references' => ['authors', 'id'],
  499. 'update' => 'cascade',
  500. 'delete' => 'cascade',
  501. ]);
  502. $this->assertEquals(['author_id_idx'], $table->constraints());
  503. }
  504. /**
  505. * Test single column foreign keys constraint support
  506. *
  507. * @return void
  508. */
  509. public function testConstraintForeignKey()
  510. {
  511. $table = $this->getTableLocator()->get('ArticlesTags');
  512. $compositeConstraint = $table->getSchema()->getConstraint('tag_id_fk');
  513. $expected = [
  514. 'type' => 'foreign',
  515. 'columns' => ['tag_id'],
  516. 'references' => ['tags', 'id'],
  517. 'update' => 'cascade',
  518. 'delete' => 'cascade',
  519. 'length' => [],
  520. ];
  521. $this->assertEquals($expected, $compositeConstraint);
  522. $expectedSubstring = 'CONSTRAINT <tag_id_fk> FOREIGN KEY \(<tag_id>\) REFERENCES <tags> \(<id>\)';
  523. $this->assertQuotedQuery($expectedSubstring, $table->getSchema()->createSql(ConnectionManager::get('test'))[0]);
  524. }
  525. /**
  526. * Test composite foreign keys support
  527. *
  528. * @return void
  529. */
  530. public function testConstraintForeignKeyTwoColumns()
  531. {
  532. $table = $this->getTableLocator()->get('Orders');
  533. $compositeConstraint = $table->getSchema()->getConstraint('product_category_fk');
  534. $expected = [
  535. 'type' => 'foreign',
  536. 'columns' => [
  537. 'product_category',
  538. 'product_id',
  539. ],
  540. 'references' => [
  541. 'products',
  542. ['category', 'id'],
  543. ],
  544. 'update' => 'cascade',
  545. 'delete' => 'cascade',
  546. 'length' => [],
  547. ];
  548. $this->assertEquals($expected, $compositeConstraint);
  549. $expectedSubstring = 'CONSTRAINT <product_category_fk> FOREIGN KEY \(<product_category>, <product_id>\)' .
  550. ' REFERENCES <products> \(<category>, <id>\)';
  551. $this->assertQuotedQuery($expectedSubstring, $table->getSchema()->createSql(ConnectionManager::get('test'))[0]);
  552. }
  553. /**
  554. * Provider for exceptionally bad foreign key data.
  555. *
  556. * @return array
  557. */
  558. public static function badForeignKeyProvider()
  559. {
  560. return [
  561. 'references is bad' => [[
  562. 'type' => TableSchema::CONSTRAINT_FOREIGN,
  563. 'columns' => ['author_id'],
  564. 'references' => ['authors'],
  565. 'delete' => 'derp',
  566. ]],
  567. 'bad update value' => [[
  568. 'type' => TableSchema::CONSTRAINT_FOREIGN,
  569. 'columns' => ['author_id'],
  570. 'references' => ['authors', 'id'],
  571. 'update' => 'derp',
  572. ]],
  573. 'bad delete value' => [[
  574. 'type' => TableSchema::CONSTRAINT_FOREIGN,
  575. 'columns' => ['author_id'],
  576. 'references' => ['authors', 'id'],
  577. 'delete' => 'derp',
  578. ]],
  579. ];
  580. }
  581. /**
  582. * Add a foreign key constraint with bad data
  583. *
  584. * @dataProvider badForeignKeyProvider
  585. * @return void
  586. */
  587. public function testAddConstraintForeignKeyBadData($data)
  588. {
  589. $this->expectException(\Cake\Database\Exception::class);
  590. $table = new TableSchema('articles');
  591. $table->addColumn('author_id', 'integer')
  592. ->addConstraint('author_id_idx', $data);
  593. }
  594. /**
  595. * Tests the setTemporary() & isTemporary() method
  596. *
  597. * @return void
  598. */
  599. public function testSetTemporary()
  600. {
  601. $table = new TableSchema('articles');
  602. $this->assertFalse($table->isTemporary());
  603. $this->assertSame($table, $table->setTemporary(true));
  604. $this->assertTrue($table->isTemporary());
  605. $table->setTemporary(false);
  606. $this->assertFalse($table->isTemporary());
  607. }
  608. /**
  609. * Assertion for comparing a regex pattern against a query having its identifiers
  610. * quoted. It accepts queries quoted with the characters `<` and `>`. If the third
  611. * parameter is set to true, it will alter the pattern to both accept quoted and
  612. * unquoted queries
  613. *
  614. * @param string $pattern
  615. * @param string $query the result to compare against
  616. * @param bool $optional
  617. * @return void
  618. */
  619. public function assertQuotedQuery($pattern, $query, $optional = false)
  620. {
  621. if ($optional) {
  622. $optional = '?';
  623. }
  624. $pattern = str_replace('<', '[`"\[]' . $optional, $pattern);
  625. $pattern = str_replace('>', '[`"\]]' . $optional, $pattern);
  626. $this->assertRegExp('#' . $pattern . '#', $query);
  627. }
  628. }