MysqlSchemaTest.php 40 KB

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