TableTest.php 20 KB

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