MysqlSchemaTest.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950
  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\Database\Connection $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. }
  545. /**
  546. * Test generating column definitions
  547. *
  548. * @dataProvider columnSqlProvider
  549. * @return void
  550. */
  551. public function testColumnSql($name, $data, $expected)
  552. {
  553. $driver = $this->_getMockedDriver();
  554. $schema = new MysqlSchema($driver);
  555. $table = (new Table('articles'))->addColumn($name, $data);
  556. $this->assertEquals($expected, $schema->columnSql($table, $name));
  557. }
  558. /**
  559. * Provide data for testing constraintSql
  560. *
  561. * @return array
  562. */
  563. public static function constraintSqlProvider()
  564. {
  565. return [
  566. [
  567. 'primary',
  568. ['type' => 'primary', 'columns' => ['title']],
  569. 'PRIMARY KEY (`title`)'
  570. ],
  571. [
  572. 'unique_idx',
  573. ['type' => 'unique', 'columns' => ['title', 'author_id']],
  574. 'UNIQUE KEY `unique_idx` (`title`, `author_id`)'
  575. ],
  576. [
  577. 'length_idx',
  578. [
  579. 'type' => 'unique',
  580. 'columns' => ['author_id', 'title'],
  581. 'length' => ['author_id' => 5, 'title' => 4]
  582. ],
  583. 'UNIQUE KEY `length_idx` (`author_id`(5), `title`(4))'
  584. ],
  585. [
  586. 'author_id_idx',
  587. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id']],
  588. 'CONSTRAINT `author_id_idx` FOREIGN KEY (`author_id`) ' .
  589. 'REFERENCES `authors` (`id`) ON UPDATE RESTRICT ON DELETE RESTRICT'
  590. ],
  591. [
  592. 'author_id_idx',
  593. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'cascade'],
  594. 'CONSTRAINT `author_id_idx` FOREIGN KEY (`author_id`) ' .
  595. 'REFERENCES `authors` (`id`) ON UPDATE CASCADE ON DELETE RESTRICT'
  596. ],
  597. [
  598. 'author_id_idx',
  599. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'restrict'],
  600. 'CONSTRAINT `author_id_idx` FOREIGN KEY (`author_id`) ' .
  601. 'REFERENCES `authors` (`id`) ON UPDATE RESTRICT ON DELETE RESTRICT'
  602. ],
  603. [
  604. 'author_id_idx',
  605. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'setNull'],
  606. 'CONSTRAINT `author_id_idx` FOREIGN KEY (`author_id`) ' .
  607. 'REFERENCES `authors` (`id`) ON UPDATE SET NULL ON DELETE RESTRICT'
  608. ],
  609. [
  610. 'author_id_idx',
  611. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'noAction'],
  612. 'CONSTRAINT `author_id_idx` FOREIGN KEY (`author_id`) ' .
  613. 'REFERENCES `authors` (`id`) ON UPDATE NO ACTION ON DELETE RESTRICT'
  614. ],
  615. ];
  616. }
  617. /**
  618. * Test the constraintSql method.
  619. *
  620. * @dataProvider constraintSqlProvider
  621. */
  622. public function testConstraintSql($name, $data, $expected)
  623. {
  624. $driver = $this->_getMockedDriver();
  625. $schema = new MysqlSchema($driver);
  626. $table = (new Table('articles'))->addColumn('title', [
  627. 'type' => 'string',
  628. 'length' => 255
  629. ])->addColumn('author_id', [
  630. 'type' => 'integer',
  631. ])->addConstraint($name, $data);
  632. $this->assertEquals($expected, $schema->constraintSql($table, $name));
  633. }
  634. /**
  635. * Test provider for indexSql()
  636. *
  637. * @return array
  638. */
  639. public static function indexSqlProvider()
  640. {
  641. return [
  642. [
  643. 'key_key',
  644. ['type' => 'index', 'columns' => ['author_id']],
  645. 'KEY `key_key` (`author_id`)'
  646. ],
  647. [
  648. 'full_text',
  649. ['type' => 'fulltext', 'columns' => ['title']],
  650. 'FULLTEXT KEY `full_text` (`title`)'
  651. ],
  652. ];
  653. }
  654. /**
  655. * Test the indexSql method.
  656. *
  657. * @dataProvider indexSqlProvider
  658. */
  659. public function testIndexSql($name, $data, $expected)
  660. {
  661. $driver = $this->_getMockedDriver();
  662. $schema = new MysqlSchema($driver);
  663. $table = (new Table('articles'))->addColumn('title', [
  664. 'type' => 'string',
  665. 'length' => 255
  666. ])->addColumn('author_id', [
  667. 'type' => 'integer',
  668. ])->addIndex($name, $data);
  669. $this->assertEquals($expected, $schema->indexSql($table, $name));
  670. }
  671. /**
  672. * Test generating a column that is a primary key.
  673. *
  674. * @return void
  675. */
  676. public function testColumnSqlPrimaryKey()
  677. {
  678. $driver = $this->_getMockedDriver();
  679. $schema = new MysqlSchema($driver);
  680. $table = new Table('articles');
  681. $table->addColumn('id', [
  682. 'type' => 'integer',
  683. 'null' => false,
  684. ])
  685. ->addConstraint('primary', [
  686. 'type' => 'primary',
  687. 'columns' => ['id']
  688. ]);
  689. $result = $schema->columnSql($table, 'id');
  690. $this->assertEquals($result, '`id` INTEGER NOT NULL AUTO_INCREMENT');
  691. $table = new Table('articles');
  692. $table->addColumn('id', [
  693. 'type' => 'biginteger',
  694. 'null' => false
  695. ])
  696. ->addConstraint('primary', [
  697. 'type' => 'primary',
  698. 'columns' => ['id']
  699. ]);
  700. $result = $schema->columnSql($table, 'id');
  701. $this->assertEquals($result, '`id` BIGINT NOT NULL AUTO_INCREMENT');
  702. }
  703. /**
  704. * Integration test for converting a Schema\Table into MySQL table creates.
  705. *
  706. * @return void
  707. */
  708. public function testCreateSql()
  709. {
  710. $driver = $this->_getMockedDriver();
  711. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  712. $connection->expects($this->any())->method('driver')
  713. ->will($this->returnValue($driver));
  714. $table = (new Table('posts'))->addColumn('id', [
  715. 'type' => 'integer',
  716. 'null' => false
  717. ])
  718. ->addColumn('title', [
  719. 'type' => 'string',
  720. 'null' => false,
  721. 'comment' => 'The title'
  722. ])
  723. ->addColumn('body', [
  724. 'type' => 'text',
  725. 'comment' => ''
  726. ])
  727. ->addColumn('created', 'datetime')
  728. ->addConstraint('primary', [
  729. 'type' => 'primary',
  730. 'columns' => ['id']
  731. ])
  732. ->options([
  733. 'engine' => 'InnoDB',
  734. 'charset' => 'utf8',
  735. 'collate' => 'utf8_general_ci',
  736. ]);
  737. $expected = <<<SQL
  738. CREATE TABLE `posts` (
  739. `id` INTEGER NOT NULL AUTO_INCREMENT,
  740. `title` VARCHAR(255) NOT NULL COMMENT "The title",
  741. `body` TEXT,
  742. `created` DATETIME,
  743. PRIMARY KEY (`id`)
  744. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci
  745. SQL;
  746. $result = $table->createSql($connection);
  747. $this->assertCount(1, $result);
  748. $this->assertTextEquals($expected, $result[0]);
  749. }
  750. /**
  751. * Tests creating temporary tables
  752. *
  753. * @return void
  754. */
  755. public function testCreateTemporary()
  756. {
  757. $driver = $this->_getMockedDriver();
  758. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  759. $connection->expects($this->any())->method('driver')
  760. ->will($this->returnValue($driver));
  761. $table = (new Table('schema_articles'))->addColumn('id', [
  762. 'type' => 'integer',
  763. 'null' => false
  764. ]);
  765. $table->temporary(true);
  766. $sql = $table->createSql($connection);
  767. $this->assertContains('CREATE TEMPORARY TABLE', $sql[0]);
  768. }
  769. /**
  770. * Test primary key generation & auto-increment.
  771. *
  772. * @return void
  773. */
  774. public function testCreateSqlCompositeIntegerKey()
  775. {
  776. $driver = $this->_getMockedDriver();
  777. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  778. $connection->expects($this->any())->method('driver')
  779. ->will($this->returnValue($driver));
  780. $table = (new Table('articles_tags'))
  781. ->addColumn('article_id', [
  782. 'type' => 'integer',
  783. 'null' => false
  784. ])
  785. ->addColumn('tag_id', [
  786. 'type' => 'integer',
  787. 'null' => false,
  788. ])
  789. ->addConstraint('primary', [
  790. 'type' => 'primary',
  791. 'columns' => ['article_id', 'tag_id']
  792. ]);
  793. $expected = <<<SQL
  794. CREATE TABLE `articles_tags` (
  795. `article_id` INTEGER NOT NULL,
  796. `tag_id` INTEGER NOT NULL,
  797. PRIMARY KEY (`article_id`, `tag_id`)
  798. )
  799. SQL;
  800. $result = $table->createSql($connection);
  801. $this->assertCount(1, $result);
  802. $this->assertTextEquals($expected, $result[0]);
  803. $table = (new Table('composite_key'))
  804. ->addColumn('id', [
  805. 'type' => 'integer',
  806. 'null' => false,
  807. 'autoIncrement' => true
  808. ])
  809. ->addColumn('account_id', [
  810. 'type' => 'integer',
  811. 'null' => false,
  812. ])
  813. ->addConstraint('primary', [
  814. 'type' => 'primary',
  815. 'columns' => ['id', 'account_id']
  816. ]);
  817. $expected = <<<SQL
  818. CREATE TABLE `composite_key` (
  819. `id` INTEGER NOT NULL AUTO_INCREMENT,
  820. `account_id` INTEGER NOT NULL,
  821. PRIMARY KEY (`id`, `account_id`)
  822. )
  823. SQL;
  824. $result = $table->createSql($connection);
  825. $this->assertCount(1, $result);
  826. $this->assertTextEquals($expected, $result[0]);
  827. }
  828. /**
  829. * test dropSql
  830. *
  831. * @return void
  832. */
  833. public function testDropSql()
  834. {
  835. $driver = $this->_getMockedDriver();
  836. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  837. $connection->expects($this->any())->method('driver')
  838. ->will($this->returnValue($driver));
  839. $table = new Table('articles');
  840. $result = $table->dropSql($connection);
  841. $this->assertCount(1, $result);
  842. $this->assertEquals('DROP TABLE `articles`', $result[0]);
  843. }
  844. /**
  845. * Test truncateSql()
  846. *
  847. * @return void
  848. */
  849. public function testTruncateSql()
  850. {
  851. $driver = $this->_getMockedDriver();
  852. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  853. $connection->expects($this->any())->method('driver')
  854. ->will($this->returnValue($driver));
  855. $table = new Table('articles');
  856. $result = $table->truncateSql($connection);
  857. $this->assertCount(1, $result);
  858. $this->assertEquals('TRUNCATE TABLE `articles`', $result[0]);
  859. }
  860. /**
  861. * Test that constructing a schema dialect connects the driver.
  862. *
  863. * @return void
  864. */
  865. public function testConstructConnectsDriver()
  866. {
  867. $driver = $this->getMock('Cake\Database\Driver');
  868. $driver->expects($this->once())
  869. ->method('connect');
  870. $schema = new MysqlSchema($driver);
  871. }
  872. /**
  873. * Get a schema instance with a mocked driver/pdo instances
  874. *
  875. * @return MysqlSchema
  876. */
  877. protected function _getMockedDriver()
  878. {
  879. $driver = new \Cake\Database\Driver\Mysql();
  880. $mock = $this->getMock('FakePdo', ['quote', 'quoteIdentifier']);
  881. $mock->expects($this->any())
  882. ->method('quote')
  883. ->will($this->returnCallback(function ($value) {
  884. return '"' . $value . '"';
  885. }));
  886. $mock->expects($this->any())
  887. ->method('quoteIdentifier')
  888. ->will($this->returnCallback(function ($value) {
  889. return '`' . $value . '`';
  890. }));
  891. $driver->connection($mock);
  892. return $driver;
  893. }
  894. }