MysqlSchemaTest.php 41 KB

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