MysqlSchemaTest.php 33 KB

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