TableTest.php 17 KB

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