MysqlSchemaTest.php 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  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\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' => 'biginteger', 'length' => 20, 'autoIncrement' => true],
  569. '`post_id` BIGINT AUTO_INCREMENT'
  570. ],
  571. // Decimal
  572. [
  573. 'value',
  574. ['type' => 'decimal'],
  575. '`value` DECIMAL'
  576. ],
  577. [
  578. 'value',
  579. ['type' => 'decimal', 'length' => 11, 'unsigned' => true],
  580. '`value` DECIMAL(11,0) UNSIGNED'
  581. ],
  582. [
  583. 'value',
  584. ['type' => 'decimal', 'length' => 12, 'precision' => 5],
  585. '`value` DECIMAL(12,5)'
  586. ],
  587. // Float
  588. [
  589. 'value',
  590. ['type' => 'float', 'unsigned'],
  591. '`value` FLOAT'
  592. ],
  593. [
  594. 'value',
  595. ['type' => 'float', 'unsigned' => true],
  596. '`value` FLOAT UNSIGNED'
  597. ],
  598. [
  599. 'value',
  600. ['type' => 'float', 'length' => 11, 'precision' => 3],
  601. '`value` FLOAT(11,3)'
  602. ],
  603. // Boolean
  604. [
  605. 'checked',
  606. ['type' => 'boolean', 'default' => false],
  607. '`checked` BOOLEAN DEFAULT FALSE'
  608. ],
  609. [
  610. 'checked',
  611. ['type' => 'boolean', 'default' => false, 'null' => false],
  612. '`checked` BOOLEAN NOT NULL DEFAULT FALSE'
  613. ],
  614. [
  615. 'checked',
  616. ['type' => 'boolean', 'default' => true, 'null' => false],
  617. '`checked` BOOLEAN NOT NULL DEFAULT TRUE'
  618. ],
  619. [
  620. 'checked',
  621. ['type' => 'boolean', 'default' => false, 'null' => true],
  622. '`checked` BOOLEAN DEFAULT FALSE'
  623. ],
  624. // datetimes
  625. [
  626. 'created',
  627. ['type' => 'datetime', 'comment' => 'Created timestamp'],
  628. '`created` DATETIME COMMENT \'Created timestamp\''
  629. ],
  630. [
  631. 'created',
  632. ['type' => 'datetime', 'null' => false, 'default' => 'current_timestamp'],
  633. '`created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP'
  634. ],
  635. [
  636. 'open_date',
  637. ['type' => 'datetime', 'null' => false, 'default' => '2016-12-07 23:04:00'],
  638. '`open_date` DATETIME NOT NULL DEFAULT \'2016-12-07 23:04:00\''
  639. ],
  640. // Date & Time
  641. [
  642. 'start_date',
  643. ['type' => 'date'],
  644. '`start_date` DATE'
  645. ],
  646. [
  647. 'start_time',
  648. ['type' => 'time'],
  649. '`start_time` TIME'
  650. ],
  651. // timestamps
  652. [
  653. 'created',
  654. ['type' => 'timestamp', 'null' => true],
  655. '`created` TIMESTAMP NULL'
  656. ],
  657. [
  658. 'created',
  659. ['type' => 'timestamp', 'null' => false, 'default' => 'current_timestamp'],
  660. '`created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP'
  661. ],
  662. [
  663. 'open_date',
  664. ['type' => 'timestamp', 'null' => false, 'default' => '2016-12-07 23:04:00'],
  665. '`open_date` TIMESTAMP NOT NULL DEFAULT \'2016-12-07 23:04:00\''
  666. ],
  667. ];
  668. }
  669. /**
  670. * Test generating column definitions
  671. *
  672. * @dataProvider columnSqlProvider
  673. * @return void
  674. */
  675. public function testColumnSql($name, $data, $expected)
  676. {
  677. $driver = $this->_getMockedDriver();
  678. $schema = new MysqlSchema($driver);
  679. $table = (new TableSchema('articles'))->addColumn($name, $data);
  680. $this->assertEquals($expected, $schema->columnSql($table, $name));
  681. }
  682. /**
  683. * Provide data for testing constraintSql
  684. *
  685. * @return array
  686. */
  687. public static function constraintSqlProvider()
  688. {
  689. return [
  690. [
  691. 'primary',
  692. ['type' => 'primary', 'columns' => ['title']],
  693. 'PRIMARY KEY (`title`)'
  694. ],
  695. [
  696. 'unique_idx',
  697. ['type' => 'unique', 'columns' => ['title', 'author_id']],
  698. 'UNIQUE KEY `unique_idx` (`title`, `author_id`)'
  699. ],
  700. [
  701. 'length_idx',
  702. [
  703. 'type' => 'unique',
  704. 'columns' => ['author_id', 'title'],
  705. 'length' => ['author_id' => 5, 'title' => 4]
  706. ],
  707. 'UNIQUE KEY `length_idx` (`author_id`(5), `title`(4))'
  708. ],
  709. [
  710. 'author_id_idx',
  711. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id']],
  712. 'CONSTRAINT `author_id_idx` FOREIGN KEY (`author_id`) ' .
  713. 'REFERENCES `authors` (`id`) ON UPDATE RESTRICT ON DELETE RESTRICT'
  714. ],
  715. [
  716. 'author_id_idx',
  717. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'cascade'],
  718. 'CONSTRAINT `author_id_idx` FOREIGN KEY (`author_id`) ' .
  719. 'REFERENCES `authors` (`id`) ON UPDATE CASCADE ON DELETE RESTRICT'
  720. ],
  721. [
  722. 'author_id_idx',
  723. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'restrict'],
  724. 'CONSTRAINT `author_id_idx` FOREIGN KEY (`author_id`) ' .
  725. 'REFERENCES `authors` (`id`) ON UPDATE RESTRICT ON DELETE RESTRICT'
  726. ],
  727. [
  728. 'author_id_idx',
  729. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'setNull'],
  730. 'CONSTRAINT `author_id_idx` FOREIGN KEY (`author_id`) ' .
  731. 'REFERENCES `authors` (`id`) ON UPDATE SET NULL ON DELETE RESTRICT'
  732. ],
  733. [
  734. 'author_id_idx',
  735. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'noAction'],
  736. 'CONSTRAINT `author_id_idx` FOREIGN KEY (`author_id`) ' .
  737. 'REFERENCES `authors` (`id`) ON UPDATE NO ACTION ON DELETE RESTRICT'
  738. ],
  739. ];
  740. }
  741. /**
  742. * Test the constraintSql method.
  743. *
  744. * @dataProvider constraintSqlProvider
  745. */
  746. public function testConstraintSql($name, $data, $expected)
  747. {
  748. $driver = $this->_getMockedDriver();
  749. $schema = new MysqlSchema($driver);
  750. $table = (new TableSchema('articles'))->addColumn('title', [
  751. 'type' => 'string',
  752. 'length' => 255
  753. ])->addColumn('author_id', [
  754. 'type' => 'integer',
  755. ])->addConstraint($name, $data);
  756. $this->assertEquals($expected, $schema->constraintSql($table, $name));
  757. }
  758. /**
  759. * Test provider for indexSql()
  760. *
  761. * @return array
  762. */
  763. public static function indexSqlProvider()
  764. {
  765. return [
  766. [
  767. 'key_key',
  768. ['type' => 'index', 'columns' => ['author_id']],
  769. 'KEY `key_key` (`author_id`)'
  770. ],
  771. [
  772. 'full_text',
  773. ['type' => 'fulltext', 'columns' => ['title']],
  774. 'FULLTEXT KEY `full_text` (`title`)'
  775. ],
  776. ];
  777. }
  778. /**
  779. * Test the indexSql method.
  780. *
  781. * @dataProvider indexSqlProvider
  782. */
  783. public function testIndexSql($name, $data, $expected)
  784. {
  785. $driver = $this->_getMockedDriver();
  786. $schema = new MysqlSchema($driver);
  787. $table = (new TableSchema('articles'))->addColumn('title', [
  788. 'type' => 'string',
  789. 'length' => 255
  790. ])->addColumn('author_id', [
  791. 'type' => 'integer',
  792. ])->addIndex($name, $data);
  793. $this->assertEquals($expected, $schema->indexSql($table, $name));
  794. }
  795. /**
  796. * Test the addConstraintSql method.
  797. *
  798. * @return void
  799. */
  800. public function testAddConstraintSql()
  801. {
  802. $driver = $this->_getMockedDriver();
  803. $connection = $this->getMockBuilder('Cake\Database\Connection')
  804. ->disableOriginalConstructor()
  805. ->getMock();
  806. $connection->expects($this->any())->method('driver')
  807. ->will($this->returnValue($driver));
  808. $table = (new TableSchema('posts'))
  809. ->addColumn('author_id', [
  810. 'type' => 'integer',
  811. 'null' => false
  812. ])
  813. ->addColumn('category_id', [
  814. 'type' => 'integer',
  815. 'null' => false
  816. ])
  817. ->addColumn('category_name', [
  818. 'type' => 'integer',
  819. 'null' => false
  820. ])
  821. ->addConstraint('author_fk', [
  822. 'type' => 'foreign',
  823. 'columns' => ['author_id'],
  824. 'references' => ['authors', 'id'],
  825. 'update' => 'cascade',
  826. 'delete' => 'cascade'
  827. ])
  828. ->addConstraint('category_fk', [
  829. 'type' => 'foreign',
  830. 'columns' => ['category_id', 'category_name'],
  831. 'references' => ['categories', ['id', 'name']],
  832. 'update' => 'cascade',
  833. 'delete' => 'cascade'
  834. ]);
  835. $expected = [
  836. 'ALTER TABLE `posts` ADD CONSTRAINT `author_fk` FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`) ON UPDATE CASCADE ON DELETE CASCADE;',
  837. 'ALTER TABLE `posts` ADD CONSTRAINT `category_fk` FOREIGN KEY (`category_id`, `category_name`) REFERENCES `categories` (`id`, `name`) ON UPDATE CASCADE ON DELETE CASCADE;'
  838. ];
  839. $result = $table->addConstraintSql($connection);
  840. $this->assertCount(2, $result);
  841. $this->assertEquals($expected, $result);
  842. }
  843. /**
  844. * Test the dropConstraintSql method.
  845. *
  846. * @return void
  847. */
  848. public function testDropConstraintSql()
  849. {
  850. $driver = $this->_getMockedDriver();
  851. $connection = $this->getMockBuilder('Cake\Database\Connection')
  852. ->disableOriginalConstructor()
  853. ->getMock();
  854. $connection->expects($this->any())->method('driver')
  855. ->will($this->returnValue($driver));
  856. $table = (new TableSchema('posts'))
  857. ->addColumn('author_id', [
  858. 'type' => 'integer',
  859. 'null' => false
  860. ])
  861. ->addColumn('category_id', [
  862. 'type' => 'integer',
  863. 'null' => false
  864. ])
  865. ->addColumn('category_name', [
  866. 'type' => 'integer',
  867. 'null' => false
  868. ])
  869. ->addConstraint('author_fk', [
  870. 'type' => 'foreign',
  871. 'columns' => ['author_id'],
  872. 'references' => ['authors', 'id'],
  873. 'update' => 'cascade',
  874. 'delete' => 'cascade'
  875. ])
  876. ->addConstraint('category_fk', [
  877. 'type' => 'foreign',
  878. 'columns' => ['category_id', 'category_name'],
  879. 'references' => ['categories', ['id', 'name']],
  880. 'update' => 'cascade',
  881. 'delete' => 'cascade'
  882. ]);
  883. $expected = [
  884. 'ALTER TABLE `posts` DROP FOREIGN KEY `author_fk`;',
  885. 'ALTER TABLE `posts` DROP FOREIGN KEY `category_fk`;'
  886. ];
  887. $result = $table->dropConstraintSql($connection);
  888. $this->assertCount(2, $result);
  889. $this->assertEquals($expected, $result);
  890. }
  891. /**
  892. * Test generating a column that is a primary key.
  893. *
  894. * @return void
  895. */
  896. public function testColumnSqlPrimaryKey()
  897. {
  898. $driver = $this->_getMockedDriver();
  899. $schema = new MysqlSchema($driver);
  900. $table = new TableSchema('articles');
  901. $table->addColumn('id', [
  902. 'type' => 'integer',
  903. 'null' => false,
  904. ])
  905. ->addConstraint('primary', [
  906. 'type' => 'primary',
  907. 'columns' => ['id']
  908. ]);
  909. $result = $schema->columnSql($table, 'id');
  910. $this->assertEquals($result, '`id` INTEGER NOT NULL AUTO_INCREMENT');
  911. $table = new TableSchema('articles');
  912. $table->addColumn('id', [
  913. 'type' => 'biginteger',
  914. 'null' => false
  915. ])
  916. ->addConstraint('primary', [
  917. 'type' => 'primary',
  918. 'columns' => ['id']
  919. ]);
  920. $result = $schema->columnSql($table, 'id');
  921. $this->assertEquals($result, '`id` BIGINT NOT NULL AUTO_INCREMENT');
  922. }
  923. /**
  924. * Integration test for converting a Schema\Table into MySQL table creates.
  925. *
  926. * @return void
  927. */
  928. public function testCreateSql()
  929. {
  930. $driver = $this->_getMockedDriver();
  931. $connection = $this->getMockBuilder('Cake\Database\Connection')
  932. ->disableOriginalConstructor()
  933. ->getMock();
  934. $connection->expects($this->any())->method('driver')
  935. ->will($this->returnValue($driver));
  936. $driver->connection()
  937. ->expects($this->any())
  938. ->method('getAttribute')
  939. ->will($this->returnValue('5.6.0'));
  940. $table = (new TableSchema('posts'))->addColumn('id', [
  941. 'type' => 'integer',
  942. 'null' => false
  943. ])
  944. ->addColumn('title', [
  945. 'type' => 'string',
  946. 'null' => false,
  947. 'comment' => 'The title'
  948. ])
  949. ->addColumn('body', [
  950. 'type' => 'text',
  951. 'comment' => ''
  952. ])
  953. ->addColumn('data', [
  954. 'type' => 'json'
  955. ])
  956. ->addColumn('hash', [
  957. 'type' => 'string',
  958. 'fixed' => true,
  959. 'length' => 40,
  960. 'collate' => 'latin1_bin',
  961. 'null' => false,
  962. ])
  963. ->addColumn('created', 'datetime')
  964. ->addConstraint('primary', [
  965. 'type' => 'primary',
  966. 'columns' => ['id']
  967. ])
  968. ->options([
  969. 'engine' => 'InnoDB',
  970. 'charset' => 'utf8',
  971. 'collate' => 'utf8_general_ci',
  972. ]);
  973. $expected = <<<SQL
  974. CREATE TABLE `posts` (
  975. `id` INTEGER NOT NULL AUTO_INCREMENT,
  976. `title` VARCHAR(255) NOT NULL COMMENT 'The title',
  977. `body` TEXT,
  978. `data` LONGTEXT,
  979. `hash` CHAR(40) COLLATE latin1_bin NOT NULL,
  980. `created` DATETIME,
  981. PRIMARY KEY (`id`)
  982. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci
  983. SQL;
  984. $result = $table->createSql($connection);
  985. $this->assertCount(1, $result);
  986. $this->assertTextEquals($expected, $result[0]);
  987. }
  988. /**
  989. * Integration test for converting a Schema\Table with native JSON
  990. *
  991. * @return void
  992. */
  993. public function testCreateSqlJson()
  994. {
  995. $driver = $this->_getMockedDriver();
  996. $connection = $this->getMockBuilder('Cake\Database\Connection')
  997. ->disableOriginalConstructor()
  998. ->getMock();
  999. $connection->expects($this->any())
  1000. ->method('driver')
  1001. ->will($this->returnValue($driver));
  1002. $driver->connection()
  1003. ->expects($this->any())
  1004. ->method('getAttribute')
  1005. ->will($this->returnValue('5.7.0'));
  1006. $table = (new TableSchema('posts'))->addColumn('id', [
  1007. 'type' => 'integer',
  1008. 'null' => false
  1009. ])
  1010. ->addColumn('data', [
  1011. 'type' => 'json'
  1012. ])
  1013. ->addConstraint('primary', [
  1014. 'type' => 'primary',
  1015. 'columns' => ['id']
  1016. ])
  1017. ->options([
  1018. 'engine' => 'InnoDB',
  1019. 'charset' => 'utf8',
  1020. 'collate' => 'utf8_general_ci',
  1021. ]);
  1022. $expected = <<<SQL
  1023. CREATE TABLE `posts` (
  1024. `id` INTEGER NOT NULL AUTO_INCREMENT,
  1025. `data` JSON,
  1026. PRIMARY KEY (`id`)
  1027. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci
  1028. SQL;
  1029. $result = $table->createSql($connection);
  1030. $this->assertCount(1, $result);
  1031. $this->assertTextEquals($expected, $result[0]);
  1032. }
  1033. /**
  1034. * Tests creating temporary tables
  1035. *
  1036. * @return void
  1037. */
  1038. public function testCreateTemporary()
  1039. {
  1040. $driver = $this->_getMockedDriver();
  1041. $connection = $this->getMockBuilder('Cake\Database\Connection')
  1042. ->disableOriginalConstructor()
  1043. ->getMock();
  1044. $connection->expects($this->any())->method('driver')
  1045. ->will($this->returnValue($driver));
  1046. $table = (new TableSchema('schema_articles'))->addColumn('id', [
  1047. 'type' => 'integer',
  1048. 'null' => false
  1049. ]);
  1050. $table->temporary(true);
  1051. $sql = $table->createSql($connection);
  1052. $this->assertContains('CREATE TEMPORARY TABLE', $sql[0]);
  1053. }
  1054. /**
  1055. * Test primary key generation & auto-increment.
  1056. *
  1057. * @return void
  1058. */
  1059. public function testCreateSqlCompositeIntegerKey()
  1060. {
  1061. $driver = $this->_getMockedDriver();
  1062. $connection = $this->getMockBuilder('Cake\Database\Connection')
  1063. ->disableOriginalConstructor()
  1064. ->getMock();
  1065. $connection->expects($this->any())->method('driver')
  1066. ->will($this->returnValue($driver));
  1067. $table = (new TableSchema('articles_tags'))
  1068. ->addColumn('article_id', [
  1069. 'type' => 'integer',
  1070. 'null' => false
  1071. ])
  1072. ->addColumn('tag_id', [
  1073. 'type' => 'integer',
  1074. 'null' => false,
  1075. ])
  1076. ->addConstraint('primary', [
  1077. 'type' => 'primary',
  1078. 'columns' => ['article_id', 'tag_id']
  1079. ]);
  1080. $expected = <<<SQL
  1081. CREATE TABLE `articles_tags` (
  1082. `article_id` INTEGER NOT NULL,
  1083. `tag_id` INTEGER NOT NULL,
  1084. PRIMARY KEY (`article_id`, `tag_id`)
  1085. )
  1086. SQL;
  1087. $result = $table->createSql($connection);
  1088. $this->assertCount(1, $result);
  1089. $this->assertTextEquals($expected, $result[0]);
  1090. $table = (new TableSchema('composite_key'))
  1091. ->addColumn('id', [
  1092. 'type' => 'integer',
  1093. 'null' => false,
  1094. 'autoIncrement' => true
  1095. ])
  1096. ->addColumn('account_id', [
  1097. 'type' => 'integer',
  1098. 'null' => false,
  1099. ])
  1100. ->addConstraint('primary', [
  1101. 'type' => 'primary',
  1102. 'columns' => ['id', 'account_id']
  1103. ]);
  1104. $expected = <<<SQL
  1105. CREATE TABLE `composite_key` (
  1106. `id` INTEGER NOT NULL AUTO_INCREMENT,
  1107. `account_id` INTEGER NOT NULL,
  1108. PRIMARY KEY (`id`, `account_id`)
  1109. )
  1110. SQL;
  1111. $result = $table->createSql($connection);
  1112. $this->assertCount(1, $result);
  1113. $this->assertTextEquals($expected, $result[0]);
  1114. }
  1115. /**
  1116. * test dropSql
  1117. *
  1118. * @return void
  1119. */
  1120. public function testDropSql()
  1121. {
  1122. $driver = $this->_getMockedDriver();
  1123. $connection = $this->getMockBuilder('Cake\Database\Connection')
  1124. ->disableOriginalConstructor()
  1125. ->getMock();
  1126. $connection->expects($this->any())->method('driver')
  1127. ->will($this->returnValue($driver));
  1128. $table = new TableSchema('articles');
  1129. $result = $table->dropSql($connection);
  1130. $this->assertCount(1, $result);
  1131. $this->assertEquals('DROP TABLE `articles`', $result[0]);
  1132. }
  1133. /**
  1134. * Test truncateSql()
  1135. *
  1136. * @return void
  1137. */
  1138. public function testTruncateSql()
  1139. {
  1140. $driver = $this->_getMockedDriver();
  1141. $connection = $this->getMockBuilder('Cake\Database\Connection')
  1142. ->disableOriginalConstructor()
  1143. ->getMock();
  1144. $connection->expects($this->any())->method('driver')
  1145. ->will($this->returnValue($driver));
  1146. $table = new TableSchema('articles');
  1147. $result = $table->truncateSql($connection);
  1148. $this->assertCount(1, $result);
  1149. $this->assertEquals('TRUNCATE TABLE `articles`', $result[0]);
  1150. }
  1151. /**
  1152. * Test that constructing a schema dialect connects the driver.
  1153. *
  1154. * @return void
  1155. */
  1156. public function testConstructConnectsDriver()
  1157. {
  1158. $driver = $this->getMockBuilder('Cake\Database\Driver')->getMock();
  1159. $driver->expects($this->once())
  1160. ->method('connect');
  1161. $schema = new MysqlSchema($driver);
  1162. }
  1163. /**
  1164. * Tests json column parsing on Mysql 5.7+
  1165. *
  1166. * @return void
  1167. */
  1168. public function testDescribeJson()
  1169. {
  1170. $connection = ConnectionManager::get('test');
  1171. $this->_createTables($connection);
  1172. $this->skipIf(!$connection->driver()->supportsNativeJson(), 'Does not support native json');
  1173. $schema = new SchemaCollection($connection);
  1174. $result = $schema->describe('schema_json');
  1175. $this->assertInstanceOf('Cake\Database\Schema\Table', $result);
  1176. $expected = [
  1177. 'type' => 'json',
  1178. 'null' => false,
  1179. 'default' => null,
  1180. 'length' => null,
  1181. 'precision' => null,
  1182. 'comment' => null,
  1183. ];
  1184. $this->assertEquals(
  1185. $expected,
  1186. $result->column('data'),
  1187. 'Field definition does not match for data'
  1188. );
  1189. }
  1190. /**
  1191. * Get a schema instance with a mocked driver/pdo instances
  1192. *
  1193. * @return MysqlSchema
  1194. */
  1195. protected function _getMockedDriver()
  1196. {
  1197. $driver = new Mysql();
  1198. $mock = $this->getMockBuilder(PDO::class)
  1199. ->setMethods(['quote', 'quoteIdentifier', 'getAttribute'])
  1200. ->disableOriginalConstructor()
  1201. ->getMock();
  1202. $mock->expects($this->any())
  1203. ->method('quote')
  1204. ->will($this->returnCallback(function ($value) {
  1205. return "'$value'";
  1206. }));
  1207. $driver->connection($mock);
  1208. return $driver;
  1209. }
  1210. }