MysqlSchemaTest.php 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204
  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\Core\Configure;
  17. use Cake\Database\Schema\Collection as SchemaCollection;
  18. use Cake\Database\Schema\MysqlSchema;
  19. use Cake\Database\Schema\Table;
  20. use Cake\Datasource\ConnectionManager;
  21. use Cake\TestSuite\TestCase;
  22. /**
  23. * Test case for Mysql Schema Dialect.
  24. */
  25. class MysqlSchemaTest extends TestCase
  26. {
  27. /**
  28. * Helper method for skipping tests that need a real connection.
  29. *
  30. * @return void
  31. */
  32. protected function _needsConnection()
  33. {
  34. $config = ConnectionManager::config('test');
  35. $this->skipIf(strpos($config['driver'], 'Mysql') === false, 'Not using Mysql for test config');
  36. }
  37. /**
  38. * Data provider for convert column testing
  39. *
  40. * @return array
  41. */
  42. public static function convertColumnProvider()
  43. {
  44. return [
  45. [
  46. 'DATETIME',
  47. ['type' => 'datetime', 'length' => null]
  48. ],
  49. [
  50. 'DATE',
  51. ['type' => 'date', 'length' => null]
  52. ],
  53. [
  54. 'TIME',
  55. ['type' => 'time', 'length' => null]
  56. ],
  57. [
  58. 'TINYINT(1)',
  59. ['type' => 'boolean', 'length' => null]
  60. ],
  61. [
  62. 'TINYINT(2)',
  63. ['type' => 'integer', 'length' => 2, 'unsigned' => false]
  64. ],
  65. [
  66. 'INTEGER(11)',
  67. ['type' => 'integer', 'length' => 11, 'unsigned' => false]
  68. ],
  69. [
  70. 'MEDIUMINT(11)',
  71. ['type' => 'integer', 'length' => 11, 'unsigned' => false]
  72. ],
  73. [
  74. 'INTEGER(11) UNSIGNED',
  75. ['type' => 'integer', 'length' => 11, 'unsigned' => true]
  76. ],
  77. [
  78. 'BIGINT',
  79. ['type' => 'biginteger', 'length' => null, 'unsigned' => false]
  80. ],
  81. [
  82. 'BIGINT UNSIGNED',
  83. ['type' => 'biginteger', 'length' => null, 'unsigned' => true]
  84. ],
  85. [
  86. 'VARCHAR(255)',
  87. ['type' => 'string', 'length' => 255]
  88. ],
  89. [
  90. 'CHAR(25)',
  91. ['type' => 'string', 'length' => 25, 'fixed' => true]
  92. ],
  93. [
  94. 'CHAR(36)',
  95. ['type' => 'uuid', 'length' => null]
  96. ],
  97. [
  98. 'TEXT',
  99. ['type' => 'text', 'length' => null]
  100. ],
  101. [
  102. 'TINYTEXT',
  103. ['type' => 'text', 'length' => Table::LENGTH_TINY]
  104. ],
  105. [
  106. 'MEDIUMTEXT',
  107. ['type' => 'text', 'length' => Table::LENGTH_MEDIUM]
  108. ],
  109. [
  110. 'LONGTEXT',
  111. ['type' => 'text', 'length' => Table::LENGTH_LONG]
  112. ],
  113. [
  114. 'TINYBLOB',
  115. ['type' => 'binary', 'length' => Table::LENGTH_TINY]
  116. ],
  117. [
  118. 'BLOB',
  119. ['type' => 'binary', 'length' => null]
  120. ],
  121. [
  122. 'MEDIUMBLOB',
  123. ['type' => 'binary', 'length' => Table::LENGTH_MEDIUM]
  124. ],
  125. [
  126. 'LONGBLOB',
  127. ['type' => 'binary', 'length' => Table::LENGTH_LONG]
  128. ],
  129. [
  130. 'FLOAT',
  131. ['type' => 'float', 'length' => null, 'precision' => null, 'unsigned' => false]
  132. ],
  133. [
  134. 'DOUBLE',
  135. ['type' => 'float', 'length' => null, 'precision' => null, 'unsigned' => false]
  136. ],
  137. [
  138. 'DOUBLE UNSIGNED',
  139. ['type' => 'float', 'length' => null, 'precision' => null, 'unsigned' => true]
  140. ],
  141. [
  142. 'DECIMAL(11,2) UNSIGNED',
  143. ['type' => 'decimal', 'length' => 11, 'precision' => 2, 'unsigned' => true]
  144. ],
  145. [
  146. 'DECIMAL(11,2)',
  147. ['type' => 'decimal', 'length' => 11, 'precision' => 2, 'unsigned' => false]
  148. ],
  149. [
  150. 'FLOAT(11,2)',
  151. ['type' => 'float', 'length' => 11, 'precision' => 2, 'unsigned' => false]
  152. ],
  153. [
  154. 'FLOAT(11,2) UNSIGNED',
  155. ['type' => 'float', 'length' => 11, 'precision' => 2, 'unsigned' => true]
  156. ],
  157. [
  158. 'DOUBLE(10,4)',
  159. ['type' => 'float', 'length' => 10, 'precision' => 4, 'unsigned' => false]
  160. ],
  161. [
  162. 'DOUBLE(10,4) UNSIGNED',
  163. ['type' => 'float', 'length' => 10, 'precision' => 4, 'unsigned' => true]
  164. ],
  165. [
  166. 'JSON',
  167. ['type' => 'json', 'length' => null]
  168. ],
  169. ];
  170. }
  171. /**
  172. * Test parsing MySQL column types from field description.
  173. *
  174. * @dataProvider convertColumnProvider
  175. * @return void
  176. */
  177. public function testConvertColumn($type, $expected)
  178. {
  179. $field = [
  180. 'Field' => 'field',
  181. 'Type' => $type,
  182. 'Null' => 'YES',
  183. 'Default' => 'Default value',
  184. 'Collation' => 'Collate information',
  185. 'Comment' => 'Comment section',
  186. ];
  187. $expected += [
  188. 'null' => true,
  189. 'default' => 'Default value',
  190. 'collate' => 'Collate information',
  191. 'comment' => 'Comment section',
  192. ];
  193. $driver = $this->getMock('Cake\Database\Driver\Mysql');
  194. $dialect = new MysqlSchema($driver);
  195. $table = $this->getMock('Cake\Database\Schema\Table', [], ['table']);
  196. $table->expects($this->at(0))->method('addColumn')->with('field', $expected);
  197. $dialect->convertColumnDescription($table, $field);
  198. }
  199. /**
  200. * Helper method for testing methods.
  201. *
  202. * @param \Cake\Datasource\ConnectionInterface $connection
  203. * @return void
  204. */
  205. protected function _createTables($connection)
  206. {
  207. $this->_needsConnection();
  208. $connection->execute('DROP TABLE IF EXISTS schema_articles');
  209. $connection->execute('DROP TABLE IF EXISTS schema_authors');
  210. $connection->execute('DROP TABLE IF EXISTS schema_json');
  211. $table = <<<SQL
  212. CREATE TABLE schema_authors (
  213. id INT(11) PRIMARY KEY AUTO_INCREMENT,
  214. name VARCHAR(50),
  215. bio TEXT,
  216. created DATETIME
  217. )ENGINE=InnoDB
  218. SQL;
  219. $connection->execute($table);
  220. $table = <<<SQL
  221. CREATE TABLE schema_articles (
  222. id BIGINT PRIMARY KEY AUTO_INCREMENT,
  223. title VARCHAR(20) COMMENT 'A title',
  224. body TEXT,
  225. author_id INT(11) NOT NULL,
  226. published BOOLEAN DEFAULT 0,
  227. allow_comments TINYINT(1) DEFAULT 0,
  228. created DATETIME,
  229. KEY `author_idx` (`author_id`),
  230. UNIQUE KEY `length_idx` (`title`(4)),
  231. FOREIGN KEY `author_idx` (`author_id`) REFERENCES `schema_authors`(`id`) ON UPDATE CASCADE ON DELETE RESTRICT
  232. ) ENGINE=InnoDB COLLATE=utf8_general_ci
  233. SQL;
  234. $connection->execute($table);
  235. if ($connection->driver()->supportsNativeJson()) {
  236. $table = <<<SQL
  237. CREATE TABLE schema_json (
  238. id INT(11) PRIMARY KEY AUTO_INCREMENT,
  239. data JSON NOT NULL
  240. )
  241. SQL;
  242. $connection->execute($table);
  243. }
  244. }
  245. /**
  246. * Integration test for SchemaCollection & MysqlDialect.
  247. *
  248. * @return void
  249. */
  250. public function testListTables()
  251. {
  252. $connection = ConnectionManager::get('test');
  253. $this->_createTables($connection);
  254. $schema = new SchemaCollection($connection);
  255. $result = $schema->listTables();
  256. $this->assertInternalType('array', $result);
  257. $this->assertContains('schema_articles', $result);
  258. $this->assertContains('schema_authors', $result);
  259. }
  260. /**
  261. * Test describing a table with Mysql
  262. *
  263. * @return void
  264. */
  265. public function testDescribeTable()
  266. {
  267. $connection = ConnectionManager::get('test');
  268. $this->_createTables($connection);
  269. $schema = new SchemaCollection($connection);
  270. $result = $schema->describe('schema_articles');
  271. $this->assertInstanceOf('Cake\Database\Schema\Table', $result);
  272. $expected = [
  273. 'id' => [
  274. 'type' => 'biginteger',
  275. 'null' => false,
  276. 'unsigned' => false,
  277. 'default' => null,
  278. 'length' => 20,
  279. 'precision' => null,
  280. 'comment' => null,
  281. 'autoIncrement' => true,
  282. ],
  283. 'title' => [
  284. 'type' => 'string',
  285. 'null' => true,
  286. 'default' => null,
  287. 'length' => 20,
  288. 'precision' => null,
  289. 'comment' => 'A title',
  290. 'fixed' => null,
  291. ],
  292. 'body' => [
  293. 'type' => 'text',
  294. 'null' => true,
  295. 'default' => null,
  296. 'length' => null,
  297. 'precision' => null,
  298. 'comment' => null,
  299. ],
  300. 'author_id' => [
  301. 'type' => 'integer',
  302. 'null' => false,
  303. 'unsigned' => false,
  304. 'default' => null,
  305. 'length' => 11,
  306. 'precision' => null,
  307. 'comment' => null,
  308. 'autoIncrement' => null,
  309. ],
  310. 'published' => [
  311. 'type' => 'boolean',
  312. 'null' => true,
  313. 'default' => 0,
  314. 'length' => null,
  315. 'precision' => null,
  316. 'comment' => null,
  317. ],
  318. 'allow_comments' => [
  319. 'type' => 'boolean',
  320. 'null' => true,
  321. 'default' => 0,
  322. 'length' => null,
  323. 'precision' => null,
  324. 'comment' => null,
  325. ],
  326. 'created' => [
  327. 'type' => 'datetime',
  328. 'null' => true,
  329. 'default' => null,
  330. 'length' => null,
  331. 'precision' => null,
  332. 'comment' => null,
  333. ],
  334. ];
  335. $this->assertEquals(['id'], $result->primaryKey());
  336. foreach ($expected as $field => $definition) {
  337. $this->assertEquals(
  338. $definition,
  339. $result->column($field),
  340. 'Field definition does not match for ' . $field
  341. );
  342. }
  343. }
  344. /**
  345. * Test describing a table with indexes in Mysql
  346. *
  347. * @return void
  348. */
  349. public function testDescribeTableIndexes()
  350. {
  351. $connection = ConnectionManager::get('test');
  352. $this->_createTables($connection);
  353. $schema = new SchemaCollection($connection);
  354. $result = $schema->describe('schema_articles');
  355. $this->assertInstanceOf('Cake\Database\Schema\Table', $result);
  356. $this->assertCount(3, $result->constraints());
  357. $expected = [
  358. 'primary' => [
  359. 'type' => 'primary',
  360. 'columns' => ['id'],
  361. 'length' => []
  362. ],
  363. 'length_idx' => [
  364. 'type' => 'unique',
  365. 'columns' => ['title'],
  366. 'length' => [
  367. 'title' => 4,
  368. ]
  369. ],
  370. 'schema_articles_ibfk_1' => [
  371. 'type' => 'foreign',
  372. 'columns' => ['author_id'],
  373. 'references' => ['schema_authors', 'id'],
  374. 'length' => [],
  375. 'update' => 'cascade',
  376. 'delete' => 'restrict',
  377. ]
  378. ];
  379. $this->assertEquals($expected['primary'], $result->constraint('primary'));
  380. $this->assertEquals($expected['length_idx'], $result->constraint('length_idx'));
  381. $this->assertEquals($expected['schema_articles_ibfk_1'], $result->constraint('schema_articles_ibfk_1'));
  382. $this->assertCount(1, $result->indexes());
  383. $expected = [
  384. 'type' => 'index',
  385. 'columns' => ['author_id'],
  386. 'length' => []
  387. ];
  388. $this->assertEquals($expected, $result->index('author_idx'));
  389. }
  390. /**
  391. * Test describing a table creates options
  392. *
  393. * @return void
  394. */
  395. public function testDescribeTableOptions()
  396. {
  397. $connection = ConnectionManager::get('test');
  398. $this->_createTables($connection);
  399. $schema = new SchemaCollection($connection);
  400. $result = $schema->describe('schema_articles');
  401. $this->assertArrayHasKey('engine', $result->options());
  402. $this->assertArrayHasKey('collation', $result->options());
  403. }
  404. public function testDescribeNonPrimaryAutoIncrement()
  405. {
  406. $this->_needsConnection();
  407. $connection = ConnectionManager::get('test');
  408. $sql = <<<SQL
  409. CREATE TABLE `odd_primary_key` (
  410. `id` BIGINT UNSIGNED NOT NULL,
  411. `other_field` INTEGER(11) NOT NULL AUTO_INCREMENT,
  412. PRIMARY KEY (`id`),
  413. UNIQUE KEY `other_field` (`other_field`)
  414. )
  415. SQL;
  416. $connection->execute($sql);
  417. $schema = new SchemaCollection($connection);
  418. $table = $schema->describe('odd_primary_key');
  419. $connection->execute('DROP TABLE odd_primary_key');
  420. $column = $table->column('id');
  421. $this->assertNull($column['autoIncrement'], 'should not autoincrement');
  422. $this->assertTrue($column['unsigned'], 'should be unsigned');
  423. $column = $table->column('other_field');
  424. $this->assertTrue($column['autoIncrement'], 'should not autoincrement');
  425. $this->assertFalse($column['unsigned'], 'should not be unsigned');
  426. $output = $table->createSql($connection);
  427. $this->assertContains('`id` BIGINT UNSIGNED NOT NULL,', $output[0]);
  428. $this->assertContains('`other_field` INTEGER(11) NOT NULL AUTO_INCREMENT,', $output[0]);
  429. }
  430. /**
  431. * Column provider for creating column sql
  432. *
  433. * @return array
  434. */
  435. public static function columnSqlProvider()
  436. {
  437. return [
  438. // strings
  439. [
  440. 'title',
  441. ['type' => 'string', 'length' => 25, 'null' => false],
  442. '`title` VARCHAR(25) NOT NULL'
  443. ],
  444. [
  445. 'title',
  446. ['type' => 'string', 'length' => 25, 'null' => true, 'default' => 'ignored'],
  447. '`title` VARCHAR(25) DEFAULT NULL'
  448. ],
  449. [
  450. 'id',
  451. ['type' => 'string', 'length' => 32, 'fixed' => true, 'null' => false],
  452. '`id` CHAR(32) NOT NULL'
  453. ],
  454. [
  455. 'role',
  456. ['type' => 'string', 'length' => 10, 'null' => false, 'default' => 'admin'],
  457. '`role` VARCHAR(10) NOT NULL DEFAULT \'admin\''
  458. ],
  459. [
  460. 'title',
  461. ['type' => 'string'],
  462. '`title` VARCHAR(255)'
  463. ],
  464. [
  465. 'id',
  466. ['type' => 'uuid'],
  467. '`id` CHAR(36)'
  468. ],
  469. // Text
  470. [
  471. 'body',
  472. ['type' => 'text', 'null' => false],
  473. '`body` TEXT NOT NULL'
  474. ],
  475. [
  476. 'body',
  477. ['type' => 'text', 'length' => Table::LENGTH_TINY, 'null' => false],
  478. '`body` TINYTEXT NOT NULL'
  479. ],
  480. [
  481. 'body',
  482. ['type' => 'text', 'length' => Table::LENGTH_MEDIUM, 'null' => false],
  483. '`body` MEDIUMTEXT NOT NULL'
  484. ],
  485. [
  486. 'body',
  487. ['type' => 'text', 'length' => Table::LENGTH_LONG, 'null' => false],
  488. '`body` LONGTEXT NOT NULL'
  489. ],
  490. // Blob / binary
  491. [
  492. 'body',
  493. ['type' => 'binary', 'null' => false],
  494. '`body` BLOB NOT NULL'
  495. ],
  496. [
  497. 'body',
  498. ['type' => 'binary', 'length' => Table::LENGTH_TINY, 'null' => false],
  499. '`body` TINYBLOB NOT NULL'
  500. ],
  501. [
  502. 'body',
  503. ['type' => 'binary', 'length' => Table::LENGTH_MEDIUM, 'null' => false],
  504. '`body` MEDIUMBLOB NOT NULL'
  505. ],
  506. [
  507. 'body',
  508. ['type' => 'binary', 'length' => Table::LENGTH_LONG, 'null' => false],
  509. '`body` LONGBLOB NOT NULL'
  510. ],
  511. // Integers
  512. [
  513. 'post_id',
  514. ['type' => 'integer', 'length' => 11],
  515. '`post_id` INTEGER(11)'
  516. ],
  517. [
  518. 'post_id',
  519. ['type' => 'integer', 'length' => 11, 'unsigned' => true],
  520. '`post_id` INTEGER(11) UNSIGNED'
  521. ],
  522. [
  523. 'post_id',
  524. ['type' => 'biginteger', 'length' => 20],
  525. '`post_id` BIGINT'
  526. ],
  527. [
  528. 'post_id',
  529. ['type' => 'biginteger', 'length' => 20, 'unsigned' => true],
  530. '`post_id` BIGINT UNSIGNED'
  531. ],
  532. [
  533. 'post_id',
  534. ['type' => 'integer', 'length' => 20, 'autoIncrement' => true],
  535. '`post_id` INTEGER(20) AUTO_INCREMENT'
  536. ],
  537. [
  538. 'post_id',
  539. ['type' => 'biginteger', 'length' => 20, 'autoIncrement' => true],
  540. '`post_id` BIGINT AUTO_INCREMENT'
  541. ],
  542. // Decimal
  543. [
  544. 'value',
  545. ['type' => 'decimal'],
  546. '`value` DECIMAL'
  547. ],
  548. [
  549. 'value',
  550. ['type' => 'decimal', 'length' => 11, 'unsigned' => true],
  551. '`value` DECIMAL(11,0) UNSIGNED'
  552. ],
  553. [
  554. 'value',
  555. ['type' => 'decimal', 'length' => 12, 'precision' => 5],
  556. '`value` DECIMAL(12,5)'
  557. ],
  558. // Float
  559. [
  560. 'value',
  561. ['type' => 'float', 'unsigned'],
  562. '`value` FLOAT'
  563. ],
  564. [
  565. 'value',
  566. ['type' => 'float', 'unsigned' => true],
  567. '`value` FLOAT UNSIGNED'
  568. ],
  569. [
  570. 'value',
  571. ['type' => 'float', 'length' => 11, 'precision' => 3],
  572. '`value` FLOAT(11,3)'
  573. ],
  574. // Boolean
  575. [
  576. 'checked',
  577. ['type' => 'boolean', 'default' => false],
  578. '`checked` BOOLEAN DEFAULT FALSE'
  579. ],
  580. [
  581. 'checked',
  582. ['type' => 'boolean', 'default' => true, 'null' => false],
  583. '`checked` BOOLEAN NOT NULL DEFAULT TRUE'
  584. ],
  585. // datetimes
  586. [
  587. 'created',
  588. ['type' => 'datetime', 'comment' => 'Created timestamp'],
  589. '`created` DATETIME COMMENT \'Created timestamp\''
  590. ],
  591. // Date & Time
  592. [
  593. 'start_date',
  594. ['type' => 'date'],
  595. '`start_date` DATE'
  596. ],
  597. [
  598. 'start_time',
  599. ['type' => 'time'],
  600. '`start_time` TIME'
  601. ],
  602. // timestamps
  603. [
  604. 'created',
  605. ['type' => 'timestamp', 'null' => true],
  606. '`created` TIMESTAMP NULL'
  607. ],
  608. [
  609. 'created',
  610. ['type' => 'timestamp', 'null' => false, 'default' => 'current_timestamp'],
  611. '`created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP'
  612. ],
  613. [
  614. 'created',
  615. ['type' => 'datetime', 'null' => false, 'default' => 'current_timestamp'],
  616. '`created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP'
  617. ],
  618. ];
  619. }
  620. /**
  621. * Test generating column definitions
  622. *
  623. * @dataProvider columnSqlProvider
  624. * @return void
  625. */
  626. public function testColumnSql($name, $data, $expected)
  627. {
  628. $driver = $this->_getMockedDriver();
  629. $schema = new MysqlSchema($driver);
  630. $table = (new Table('articles'))->addColumn($name, $data);
  631. $this->assertEquals($expected, $schema->columnSql($table, $name));
  632. }
  633. /**
  634. * Provide data for testing constraintSql
  635. *
  636. * @return array
  637. */
  638. public static function constraintSqlProvider()
  639. {
  640. return [
  641. [
  642. 'primary',
  643. ['type' => 'primary', 'columns' => ['title']],
  644. 'PRIMARY KEY (`title`)'
  645. ],
  646. [
  647. 'unique_idx',
  648. ['type' => 'unique', 'columns' => ['title', 'author_id']],
  649. 'UNIQUE KEY `unique_idx` (`title`, `author_id`)'
  650. ],
  651. [
  652. 'length_idx',
  653. [
  654. 'type' => 'unique',
  655. 'columns' => ['author_id', 'title'],
  656. 'length' => ['author_id' => 5, 'title' => 4]
  657. ],
  658. 'UNIQUE KEY `length_idx` (`author_id`(5), `title`(4))'
  659. ],
  660. [
  661. 'author_id_idx',
  662. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id']],
  663. 'CONSTRAINT `author_id_idx` FOREIGN KEY (`author_id`) ' .
  664. 'REFERENCES `authors` (`id`) ON UPDATE RESTRICT ON DELETE RESTRICT'
  665. ],
  666. [
  667. 'author_id_idx',
  668. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'cascade'],
  669. 'CONSTRAINT `author_id_idx` FOREIGN KEY (`author_id`) ' .
  670. 'REFERENCES `authors` (`id`) ON UPDATE CASCADE ON DELETE RESTRICT'
  671. ],
  672. [
  673. 'author_id_idx',
  674. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'restrict'],
  675. 'CONSTRAINT `author_id_idx` FOREIGN KEY (`author_id`) ' .
  676. 'REFERENCES `authors` (`id`) ON UPDATE RESTRICT ON DELETE RESTRICT'
  677. ],
  678. [
  679. 'author_id_idx',
  680. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'setNull'],
  681. 'CONSTRAINT `author_id_idx` FOREIGN KEY (`author_id`) ' .
  682. 'REFERENCES `authors` (`id`) ON UPDATE SET NULL ON DELETE RESTRICT'
  683. ],
  684. [
  685. 'author_id_idx',
  686. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'noAction'],
  687. 'CONSTRAINT `author_id_idx` FOREIGN KEY (`author_id`) ' .
  688. 'REFERENCES `authors` (`id`) ON UPDATE NO ACTION ON DELETE RESTRICT'
  689. ],
  690. ];
  691. }
  692. /**
  693. * Test the constraintSql method.
  694. *
  695. * @dataProvider constraintSqlProvider
  696. */
  697. public function testConstraintSql($name, $data, $expected)
  698. {
  699. $driver = $this->_getMockedDriver();
  700. $schema = new MysqlSchema($driver);
  701. $table = (new Table('articles'))->addColumn('title', [
  702. 'type' => 'string',
  703. 'length' => 255
  704. ])->addColumn('author_id', [
  705. 'type' => 'integer',
  706. ])->addConstraint($name, $data);
  707. $this->assertEquals($expected, $schema->constraintSql($table, $name));
  708. }
  709. /**
  710. * Test provider for indexSql()
  711. *
  712. * @return array
  713. */
  714. public static function indexSqlProvider()
  715. {
  716. return [
  717. [
  718. 'key_key',
  719. ['type' => 'index', 'columns' => ['author_id']],
  720. 'KEY `key_key` (`author_id`)'
  721. ],
  722. [
  723. 'full_text',
  724. ['type' => 'fulltext', 'columns' => ['title']],
  725. 'FULLTEXT KEY `full_text` (`title`)'
  726. ],
  727. ];
  728. }
  729. /**
  730. * Test the indexSql method.
  731. *
  732. * @dataProvider indexSqlProvider
  733. */
  734. public function testIndexSql($name, $data, $expected)
  735. {
  736. $driver = $this->_getMockedDriver();
  737. $schema = new MysqlSchema($driver);
  738. $table = (new Table('articles'))->addColumn('title', [
  739. 'type' => 'string',
  740. 'length' => 255
  741. ])->addColumn('author_id', [
  742. 'type' => 'integer',
  743. ])->addIndex($name, $data);
  744. $this->assertEquals($expected, $schema->indexSql($table, $name));
  745. }
  746. /**
  747. * Test the addConstraintSql method.
  748. *
  749. * @return void
  750. */
  751. public function testAddConstraintSql()
  752. {
  753. $driver = $this->_getMockedDriver();
  754. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  755. $connection->expects($this->any())->method('driver')
  756. ->will($this->returnValue($driver));
  757. $table = (new Table('posts'))
  758. ->addColumn('author_id', [
  759. 'type' => 'integer',
  760. 'null' => false
  761. ])
  762. ->addColumn('category_id', [
  763. 'type' => 'integer',
  764. 'null' => false
  765. ])
  766. ->addColumn('category_name', [
  767. 'type' => 'integer',
  768. 'null' => false
  769. ])
  770. ->addConstraint('author_fk', [
  771. 'type' => 'foreign',
  772. 'columns' => ['author_id'],
  773. 'references' => ['authors', 'id'],
  774. 'update' => 'cascade',
  775. 'delete' => 'cascade'
  776. ])
  777. ->addConstraint('category_fk', [
  778. 'type' => 'foreign',
  779. 'columns' => ['category_id', 'category_name'],
  780. 'references' => ['categories', ['id', 'name']],
  781. 'update' => 'cascade',
  782. 'delete' => 'cascade'
  783. ]);
  784. $expected = [
  785. 'ALTER TABLE `posts` ADD CONSTRAINT `author_fk` FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`) ON UPDATE CASCADE ON DELETE CASCADE;',
  786. 'ALTER TABLE `posts` ADD CONSTRAINT `category_fk` FOREIGN KEY (`category_id`, `category_name`) REFERENCES `categories` (`id`, `name`) ON UPDATE CASCADE ON DELETE CASCADE;'
  787. ];
  788. $result = $table->addConstraintSql($connection);
  789. $this->assertCount(2, $result);
  790. $this->assertEquals($expected, $result);
  791. }
  792. /**
  793. * Test the dropConstraintSql method.
  794. *
  795. * @return void
  796. */
  797. public function testDropConstraintSql()
  798. {
  799. $driver = $this->_getMockedDriver();
  800. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  801. $connection->expects($this->any())->method('driver')
  802. ->will($this->returnValue($driver));
  803. $table = (new Table('posts'))
  804. ->addColumn('author_id', [
  805. 'type' => 'integer',
  806. 'null' => false
  807. ])
  808. ->addColumn('category_id', [
  809. 'type' => 'integer',
  810. 'null' => false
  811. ])
  812. ->addColumn('category_name', [
  813. 'type' => 'integer',
  814. 'null' => false
  815. ])
  816. ->addConstraint('author_fk', [
  817. 'type' => 'foreign',
  818. 'columns' => ['author_id'],
  819. 'references' => ['authors', 'id'],
  820. 'update' => 'cascade',
  821. 'delete' => 'cascade'
  822. ])
  823. ->addConstraint('category_fk', [
  824. 'type' => 'foreign',
  825. 'columns' => ['category_id', 'category_name'],
  826. 'references' => ['categories', ['id', 'name']],
  827. 'update' => 'cascade',
  828. 'delete' => 'cascade'
  829. ]);
  830. $expected = [
  831. 'ALTER TABLE `posts` DROP FOREIGN KEY `author_fk`;',
  832. 'ALTER TABLE `posts` DROP FOREIGN KEY `category_fk`;'
  833. ];
  834. $result = $table->dropConstraintSql($connection);
  835. $this->assertCount(2, $result);
  836. $this->assertEquals($expected, $result);
  837. }
  838. /**
  839. * Test generating a column that is a primary key.
  840. *
  841. * @return void
  842. */
  843. public function testColumnSqlPrimaryKey()
  844. {
  845. $driver = $this->_getMockedDriver();
  846. $schema = new MysqlSchema($driver);
  847. $table = new Table('articles');
  848. $table->addColumn('id', [
  849. 'type' => 'integer',
  850. 'null' => false,
  851. ])
  852. ->addConstraint('primary', [
  853. 'type' => 'primary',
  854. 'columns' => ['id']
  855. ]);
  856. $result = $schema->columnSql($table, 'id');
  857. $this->assertEquals($result, '`id` INTEGER NOT NULL AUTO_INCREMENT');
  858. $table = new Table('articles');
  859. $table->addColumn('id', [
  860. 'type' => 'biginteger',
  861. 'null' => false
  862. ])
  863. ->addConstraint('primary', [
  864. 'type' => 'primary',
  865. 'columns' => ['id']
  866. ]);
  867. $result = $schema->columnSql($table, 'id');
  868. $this->assertEquals($result, '`id` BIGINT NOT NULL AUTO_INCREMENT');
  869. }
  870. /**
  871. * Integration test for converting a Schema\Table into MySQL table creates.
  872. *
  873. * @return void
  874. */
  875. public function testCreateSql()
  876. {
  877. $driver = $this->_getMockedDriver();
  878. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  879. $connection->expects($this->any())->method('driver')
  880. ->will($this->returnValue($driver));
  881. $driver->connection()
  882. ->expects($this->any())
  883. ->method('getAttribute')
  884. ->will($this->returnValue('5.6.0'));
  885. $table = (new Table('posts'))->addColumn('id', [
  886. 'type' => 'integer',
  887. 'null' => false
  888. ])
  889. ->addColumn('title', [
  890. 'type' => 'string',
  891. 'null' => false,
  892. 'comment' => 'The title'
  893. ])
  894. ->addColumn('body', [
  895. 'type' => 'text',
  896. 'comment' => ''
  897. ])
  898. ->addColumn('data', [
  899. 'type' => 'json'
  900. ])
  901. ->addColumn('created', 'datetime')
  902. ->addConstraint('primary', [
  903. 'type' => 'primary',
  904. 'columns' => ['id']
  905. ])
  906. ->options([
  907. 'engine' => 'InnoDB',
  908. 'charset' => 'utf8',
  909. 'collate' => 'utf8_general_ci',
  910. ]);
  911. $expected = <<<SQL
  912. CREATE TABLE `posts` (
  913. `id` INTEGER NOT NULL AUTO_INCREMENT,
  914. `title` VARCHAR(255) NOT NULL COMMENT 'The title',
  915. `body` TEXT,
  916. `data` LONGTEXT,
  917. `created` DATETIME,
  918. PRIMARY KEY (`id`)
  919. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci
  920. SQL;
  921. $result = $table->createSql($connection);
  922. $this->assertCount(1, $result);
  923. $this->assertTextEquals($expected, $result[0]);
  924. }
  925. /**
  926. * Integration test for converting a Schema\Table with native JSON
  927. *
  928. * @return void
  929. */
  930. public function testCreateSqlJson()
  931. {
  932. $driver = $this->_getMockedDriver();
  933. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  934. $connection->expects($this->any())
  935. ->method('driver')
  936. ->will($this->returnValue($driver));
  937. $driver->connection()
  938. ->expects($this->any())
  939. ->method('getAttribute')
  940. ->will($this->returnValue('5.7.0'));
  941. $table = (new Table('posts'))->addColumn('id', [
  942. 'type' => 'integer',
  943. 'null' => false
  944. ])
  945. ->addColumn('data', [
  946. 'type' => 'json'
  947. ])
  948. ->addConstraint('primary', [
  949. 'type' => 'primary',
  950. 'columns' => ['id']
  951. ])
  952. ->options([
  953. 'engine' => 'InnoDB',
  954. 'charset' => 'utf8',
  955. 'collate' => 'utf8_general_ci',
  956. ]);
  957. $expected = <<<SQL
  958. CREATE TABLE `posts` (
  959. `id` INTEGER NOT NULL AUTO_INCREMENT,
  960. `data` JSON,
  961. PRIMARY KEY (`id`)
  962. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci
  963. SQL;
  964. $result = $table->createSql($connection);
  965. $this->assertCount(1, $result);
  966. $this->assertTextEquals($expected, $result[0]);
  967. }
  968. /**
  969. * Tests creating temporary tables
  970. *
  971. * @return void
  972. */
  973. public function testCreateTemporary()
  974. {
  975. $driver = $this->_getMockedDriver();
  976. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  977. $connection->expects($this->any())->method('driver')
  978. ->will($this->returnValue($driver));
  979. $table = (new Table('schema_articles'))->addColumn('id', [
  980. 'type' => 'integer',
  981. 'null' => false
  982. ]);
  983. $table->temporary(true);
  984. $sql = $table->createSql($connection);
  985. $this->assertContains('CREATE TEMPORARY TABLE', $sql[0]);
  986. }
  987. /**
  988. * Test primary key generation & auto-increment.
  989. *
  990. * @return void
  991. */
  992. public function testCreateSqlCompositeIntegerKey()
  993. {
  994. $driver = $this->_getMockedDriver();
  995. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  996. $connection->expects($this->any())->method('driver')
  997. ->will($this->returnValue($driver));
  998. $table = (new Table('articles_tags'))
  999. ->addColumn('article_id', [
  1000. 'type' => 'integer',
  1001. 'null' => false
  1002. ])
  1003. ->addColumn('tag_id', [
  1004. 'type' => 'integer',
  1005. 'null' => false,
  1006. ])
  1007. ->addConstraint('primary', [
  1008. 'type' => 'primary',
  1009. 'columns' => ['article_id', 'tag_id']
  1010. ]);
  1011. $expected = <<<SQL
  1012. CREATE TABLE `articles_tags` (
  1013. `article_id` INTEGER NOT NULL,
  1014. `tag_id` INTEGER NOT NULL,
  1015. PRIMARY KEY (`article_id`, `tag_id`)
  1016. )
  1017. SQL;
  1018. $result = $table->createSql($connection);
  1019. $this->assertCount(1, $result);
  1020. $this->assertTextEquals($expected, $result[0]);
  1021. $table = (new Table('composite_key'))
  1022. ->addColumn('id', [
  1023. 'type' => 'integer',
  1024. 'null' => false,
  1025. 'autoIncrement' => true
  1026. ])
  1027. ->addColumn('account_id', [
  1028. 'type' => 'integer',
  1029. 'null' => false,
  1030. ])
  1031. ->addConstraint('primary', [
  1032. 'type' => 'primary',
  1033. 'columns' => ['id', 'account_id']
  1034. ]);
  1035. $expected = <<<SQL
  1036. CREATE TABLE `composite_key` (
  1037. `id` INTEGER NOT NULL AUTO_INCREMENT,
  1038. `account_id` INTEGER NOT NULL,
  1039. PRIMARY KEY (`id`, `account_id`)
  1040. )
  1041. SQL;
  1042. $result = $table->createSql($connection);
  1043. $this->assertCount(1, $result);
  1044. $this->assertTextEquals($expected, $result[0]);
  1045. }
  1046. /**
  1047. * test dropSql
  1048. *
  1049. * @return void
  1050. */
  1051. public function testDropSql()
  1052. {
  1053. $driver = $this->_getMockedDriver();
  1054. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  1055. $connection->expects($this->any())->method('driver')
  1056. ->will($this->returnValue($driver));
  1057. $table = new Table('articles');
  1058. $result = $table->dropSql($connection);
  1059. $this->assertCount(1, $result);
  1060. $this->assertEquals('DROP TABLE `articles`', $result[0]);
  1061. }
  1062. /**
  1063. * Test truncateSql()
  1064. *
  1065. * @return void
  1066. */
  1067. public function testTruncateSql()
  1068. {
  1069. $driver = $this->_getMockedDriver();
  1070. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  1071. $connection->expects($this->any())->method('driver')
  1072. ->will($this->returnValue($driver));
  1073. $table = new Table('articles');
  1074. $result = $table->truncateSql($connection);
  1075. $this->assertCount(1, $result);
  1076. $this->assertEquals('TRUNCATE TABLE `articles`', $result[0]);
  1077. }
  1078. /**
  1079. * Test that constructing a schema dialect connects the driver.
  1080. *
  1081. * @return void
  1082. */
  1083. public function testConstructConnectsDriver()
  1084. {
  1085. $driver = $this->getMock('Cake\Database\Driver');
  1086. $driver->expects($this->once())
  1087. ->method('connect');
  1088. $schema = new MysqlSchema($driver);
  1089. }
  1090. /**
  1091. * Tests json column parsing on Mysql 5.7+
  1092. *
  1093. * @return void
  1094. */
  1095. public function testDescribeJson()
  1096. {
  1097. $connection = ConnectionManager::get('test');
  1098. $this->_createTables($connection);
  1099. $this->skipIf(!$connection->driver()->supportsNativeJson(), 'Does not support native json');
  1100. $schema = new SchemaCollection($connection);
  1101. $result = $schema->describe('schema_json');
  1102. $this->assertInstanceOf('Cake\Database\Schema\Table', $result);
  1103. $expected = [
  1104. 'type' => 'json',
  1105. 'null' => false,
  1106. 'default' => null,
  1107. 'length' => null,
  1108. 'precision' => null,
  1109. 'comment' => null,
  1110. ];
  1111. $this->assertEquals(
  1112. $expected,
  1113. $result->column('data'),
  1114. 'Field definition does not match for data'
  1115. );
  1116. }
  1117. /**
  1118. * Get a schema instance with a mocked driver/pdo instances
  1119. *
  1120. * @return MysqlSchema
  1121. */
  1122. protected function _getMockedDriver()
  1123. {
  1124. $driver = new \Cake\Database\Driver\Mysql();
  1125. $mock = $this->getMock('FakePdo', ['quote', 'quoteIdentifier', 'getAttribute']);
  1126. $mock->expects($this->any())
  1127. ->method('quote')
  1128. ->will($this->returnCallback(function ($value) {
  1129. return "'$value'";
  1130. }));
  1131. $driver->connection($mock);
  1132. return $driver;
  1133. }
  1134. }