TableSchemaTest.php 20 KB

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