MysqlSchemaTest.php 34 KB

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