MysqlSchemaTest.php 42 KB

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