MysqlSchemaTest.php 46 KB

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