TableTest.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  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.orders', 'core.products', '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. 'length' => null,
  192. 'precision' => null,
  193. 'default' => null,
  194. 'null' => null,
  195. 'fixed' => null,
  196. 'comment' => null,
  197. ];
  198. $this->assertEquals($expected, $result);
  199. $table->addColumn('author_id', [
  200. 'type' => 'integer'
  201. ]);
  202. $result = $table->column('author_id');
  203. $expected = [
  204. 'type' => 'integer',
  205. 'length' => null,
  206. 'precision' => null,
  207. 'default' => null,
  208. 'null' => null,
  209. 'unsigned' => null,
  210. 'comment' => null,
  211. 'autoIncrement' => null,
  212. ];
  213. $this->assertEquals($expected, $result);
  214. $table->addColumn('amount', [
  215. 'type' => 'decimal'
  216. ]);
  217. $result = $table->column('amount');
  218. $expected = [
  219. 'type' => 'decimal',
  220. 'length' => null,
  221. 'precision' => null,
  222. 'default' => null,
  223. 'null' => null,
  224. 'unsigned' => null,
  225. 'comment' => null,
  226. ];
  227. $this->assertEquals($expected, $result);
  228. }
  229. /**
  230. * Test reading default values.
  231. *
  232. * @return void
  233. */
  234. public function testDefaultValues()
  235. {
  236. $table = new Table('articles');
  237. $table->addColumn('id', [
  238. 'type' => 'integer',
  239. 'default' => 0
  240. ])->addColumn('title', [
  241. 'type' => 'string',
  242. 'default' => 'A title'
  243. ])->addColumn('name', [
  244. 'type' => 'string',
  245. 'null' => false,
  246. 'default' => null,
  247. ])->addColumn('body', [
  248. 'type' => 'text',
  249. 'null' => true,
  250. 'default' => null,
  251. ]);
  252. $result = $table->defaultValues();
  253. $expected = [
  254. 'id' => 0,
  255. 'title' => 'A title',
  256. 'body' => null
  257. ];
  258. $this->assertEquals($expected, $result);
  259. }
  260. /**
  261. * Test adding an constraint.
  262. * >
  263. * @return void
  264. */
  265. public function testAddConstraint()
  266. {
  267. $table = new Table('articles');
  268. $table->addColumn('id', [
  269. 'type' => 'integer'
  270. ]);
  271. $result = $table->addConstraint('primary', [
  272. 'type' => 'primary',
  273. 'columns' => ['id']
  274. ]);
  275. $this->assertSame($result, $table);
  276. $this->assertEquals(['primary'], $table->constraints());
  277. }
  278. /**
  279. * Dataprovider for invalid addConstraint calls.
  280. *
  281. * @return array
  282. */
  283. public static function addConstaintErrorProvider()
  284. {
  285. return [
  286. // No properties
  287. [[]],
  288. // Empty columns
  289. [['columns' => '', 'type' => Table::CONSTRAINT_UNIQUE]],
  290. [['columns' => [], 'type' => Table::CONSTRAINT_UNIQUE]],
  291. // Missing column
  292. [['columns' => ['derp'], 'type' => Table::CONSTRAINT_UNIQUE]],
  293. // Invalid type
  294. [['columns' => 'author_id', 'type' => 'derp']],
  295. ];
  296. }
  297. /**
  298. * Test that an exception is raised when constraints
  299. * are added for fields that do not exist.
  300. *
  301. * @dataProvider addConstaintErrorProvider
  302. * @expectedException \Cake\Database\Exception
  303. * @return void
  304. */
  305. public function testAddConstraintError($props)
  306. {
  307. $table = new Table('articles');
  308. $table->addColumn('author_id', 'integer');
  309. $table->addConstraint('author_idx', $props);
  310. }
  311. /**
  312. * Test adding an index.
  313. *
  314. * @return void
  315. */
  316. public function testAddIndex()
  317. {
  318. $table = new Table('articles');
  319. $table->addColumn('title', [
  320. 'type' => 'string'
  321. ]);
  322. $result = $table->addIndex('faster', [
  323. 'type' => 'index',
  324. 'columns' => ['title']
  325. ]);
  326. $this->assertSame($result, $table);
  327. $this->assertEquals(['faster'], $table->indexes());
  328. }
  329. /**
  330. * Dataprovider for invalid addIndex calls
  331. *
  332. * @return array
  333. */
  334. public static function addIndexErrorProvider()
  335. {
  336. return [
  337. // Empty
  338. [[]],
  339. // Invalid type
  340. [['columns' => 'author_id', 'type' => 'derp']],
  341. // No columns
  342. [['columns' => ''], 'type' => Table::INDEX_INDEX],
  343. [['columns' => [], 'type' => Table::INDEX_INDEX]],
  344. // Missing column
  345. [['columns' => ['not_there'], 'type' => Table::INDEX_INDEX]],
  346. ];
  347. }
  348. /**
  349. * Test that an exception is raised when indexes
  350. * are added for fields that do not exist.
  351. *
  352. * @dataProvider addIndexErrorProvider
  353. * @expectedException \Cake\Database\Exception
  354. * @return void
  355. */
  356. public function testAddIndexError($props)
  357. {
  358. $table = new Table('articles');
  359. $table->addColumn('author_id', 'integer');
  360. $table->addIndex('author_idx', $props);
  361. }
  362. /**
  363. * Test adding different kinds of indexes.
  364. *
  365. * @return void
  366. */
  367. public function testAddIndexTypes()
  368. {
  369. $table = new Table('articles');
  370. $table->addColumn('id', 'integer')
  371. ->addColumn('title', 'string')
  372. ->addColumn('author_id', 'integer');
  373. $table->addIndex('author_idx', [
  374. 'columns' => ['author_id'],
  375. 'type' => 'index'
  376. ])->addIndex('texty', [
  377. 'type' => 'fulltext',
  378. 'columns' => ['title']
  379. ]);
  380. $this->assertEquals(
  381. ['author_idx', 'texty'],
  382. $table->indexes()
  383. );
  384. }
  385. /**
  386. * Test getting the primary key.
  387. *
  388. * @return void
  389. */
  390. public function testPrimaryKey()
  391. {
  392. $table = new Table('articles');
  393. $table->addColumn('id', 'integer')
  394. ->addColumn('title', 'string')
  395. ->addColumn('author_id', 'integer')
  396. ->addConstraint('author_idx', [
  397. 'columns' => ['author_id'],
  398. 'type' => 'unique'
  399. ])->addConstraint('primary', [
  400. 'type' => 'primary',
  401. 'columns' => ['id']
  402. ]);
  403. $this->assertEquals(['id'], $table->primaryKey());
  404. $table = new Table('articles');
  405. $table->addColumn('id', 'integer')
  406. ->addColumn('title', 'string')
  407. ->addColumn('author_id', 'integer');
  408. $this->assertEquals([], $table->primaryKey());
  409. }
  410. /**
  411. * Test the options method.
  412. *
  413. * @return void
  414. */
  415. public function testOptions()
  416. {
  417. $table = new Table('articles');
  418. $options = [
  419. 'engine' => 'InnoDB'
  420. ];
  421. $return = $table->options($options);
  422. $this->assertInstanceOf('Cake\Database\Schema\Table', $return);
  423. $this->assertEquals($options, $table->options());
  424. }
  425. /**
  426. * Add a basic foreign key constraint.
  427. *
  428. * @return void
  429. */
  430. public function testAddConstraintForeignKey()
  431. {
  432. $table = new Table('articles');
  433. $table->addColumn('author_id', 'integer')
  434. ->addConstraint('author_id_idx', [
  435. 'type' => Table::CONSTRAINT_FOREIGN,
  436. 'columns' => ['author_id'],
  437. 'references' => ['authors', 'id'],
  438. 'update' => 'cascade',
  439. 'delete' => 'cascade',
  440. ]);
  441. $this->assertEquals(['author_id_idx'], $table->constraints());
  442. }
  443. /**
  444. * Test single column foreign keys constraint support
  445. *
  446. * @return void
  447. */
  448. public function testConstraintForeignKey()
  449. {
  450. $table = TableRegistry::get('ArticlesTags');
  451. $compositeConstraint = $table->schema()->constraint('tag_id_fk');
  452. $expected = [
  453. 'type' => 'foreign',
  454. 'columns' => ['tag_id'],
  455. 'references' => ['tags', 'id'],
  456. 'update' => 'cascade',
  457. 'delete' => 'cascade',
  458. 'length' => []
  459. ];
  460. $this->assertEquals($expected, $compositeConstraint);
  461. $expectedSubstring = 'CONSTRAINT <tag_id_fk> FOREIGN KEY \(<tag_id>\) REFERENCES <tags> \(<id>\)';
  462. $this->assertQuotedQuery($expectedSubstring, $table->schema()->createSql(ConnectionManager::get('test'))[0]);
  463. }
  464. /**
  465. * Test composite foreign keys support
  466. *
  467. * @return void
  468. */
  469. public function testConstraintForeignKeyTwoColumns()
  470. {
  471. $table = TableRegistry::get('Orders');
  472. $compositeConstraint = $table->schema()->constraint('product_id_fk');
  473. $expected = [
  474. 'type' => 'foreign',
  475. 'columns' => [
  476. 'product_category',
  477. 'product_id'
  478. ],
  479. 'references' => [
  480. 'products',
  481. ['category', 'id']
  482. ],
  483. 'update' => 'cascade',
  484. 'delete' => 'cascade',
  485. 'length' => []
  486. ];
  487. $this->assertEquals($expected, $compositeConstraint);
  488. $expectedSubstring = 'CONSTRAINT <product_id_fk> FOREIGN KEY \(<product_category>, <product_id>\)' .
  489. ' REFERENCES <products> \(<category>, <id>\)';
  490. $this->assertQuotedQuery($expectedSubstring, $table->schema()->createSql(ConnectionManager::get('test'))[0]);
  491. }
  492. /**
  493. * Provider for exceptionally bad foreign key data.
  494. *
  495. * @return array
  496. */
  497. public static function badForeignKeyProvider()
  498. {
  499. return [
  500. 'references is bad' => [[
  501. 'type' => Table::CONSTRAINT_FOREIGN,
  502. 'columns' => ['author_id'],
  503. 'references' => ['authors'],
  504. 'delete' => 'derp',
  505. ]],
  506. 'bad update value' => [[
  507. 'type' => Table::CONSTRAINT_FOREIGN,
  508. 'columns' => ['author_id'],
  509. 'references' => ['authors', 'id'],
  510. 'update' => 'derp',
  511. ]],
  512. 'bad delete value' => [[
  513. 'type' => Table::CONSTRAINT_FOREIGN,
  514. 'columns' => ['author_id'],
  515. 'references' => ['authors', 'id'],
  516. 'delete' => 'derp',
  517. ]],
  518. ];
  519. }
  520. /**
  521. * Add a foreign key constraint with bad data
  522. *
  523. * @dataProvider badForeignKeyProvider
  524. * @expectedException \Cake\Database\Exception
  525. * @return void
  526. */
  527. public function testAddConstraintForeignKeyBadData($data)
  528. {
  529. $table = new Table('articles');
  530. $table->addColumn('author_id', 'integer')
  531. ->addConstraint('author_id_idx', $data);
  532. }
  533. /**
  534. * Tests the temporary() method
  535. *
  536. * @return void
  537. */
  538. public function testTemporary()
  539. {
  540. $table = new Table('articles');
  541. $this->assertFalse($table->temporary());
  542. $this->assertSame($table, $table->temporary(true));
  543. $this->assertTrue($table->temporary());
  544. $table->temporary(false);
  545. $this->assertFalse($table->temporary());
  546. }
  547. /**
  548. * Assertion for comparing a regex pattern against a query having its identifiers
  549. * quoted. It accepts queries quoted with the characters `<` and `>`. If the third
  550. * parameter is set to true, it will alter the pattern to both accept quoted and
  551. * unquoted queries
  552. *
  553. * @param string $pattern
  554. * @param string $query the result to compare against
  555. * @param bool $optional
  556. * @return void
  557. */
  558. public function assertQuotedQuery($pattern, $query, $optional = false)
  559. {
  560. if ($optional) {
  561. $optional = '?';
  562. }
  563. $pattern = str_replace('<', '[`"\[]' . $optional, $pattern);
  564. $pattern = str_replace('>', '[`"\]]' . $optional, $pattern);
  565. $this->assertRegExp('#' . $pattern . '#', $query);
  566. }
  567. }