MysqlSchemaTest.php 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392
  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. $resultAll = $schema->listTablesAndViews();
  312. $resultNoViews = $schema->listTablesWithoutViews();
  313. $this->assertIsArray($resultAll);
  314. $this->assertContains('schema_articles', $resultAll);
  315. $this->assertContains('schema_articles_v', $resultAll);
  316. $this->assertContains('schema_authors', $resultAll);
  317. $this->assertIsArray($resultNoViews);
  318. $this->assertNotContains('schema_articles_v', $resultNoViews);
  319. $this->assertContains('schema_articles', $resultNoViews);
  320. }
  321. /**
  322. * Test describing a table with MySQL
  323. */
  324. public function testDescribeTable(): void
  325. {
  326. $connection = ConnectionManager::get('test');
  327. $this->_createTables($connection);
  328. $schema = new SchemaCollection($connection);
  329. $result = $schema->describe('schema_articles');
  330. $this->assertInstanceOf('Cake\Database\Schema\TableSchema', $result);
  331. $expected = [
  332. 'id' => [
  333. 'type' => 'biginteger',
  334. 'null' => false,
  335. 'unsigned' => false,
  336. 'default' => null,
  337. 'length' => null,
  338. 'precision' => null,
  339. 'comment' => null,
  340. 'autoIncrement' => true,
  341. ],
  342. 'title' => [
  343. 'type' => 'string',
  344. 'null' => true,
  345. 'default' => null,
  346. 'length' => 20,
  347. 'precision' => null,
  348. 'comment' => 'A title',
  349. 'collate' => 'utf8_general_ci',
  350. ],
  351. 'body' => [
  352. 'type' => 'text',
  353. 'null' => true,
  354. 'default' => null,
  355. 'length' => null,
  356. 'precision' => null,
  357. 'comment' => null,
  358. 'collate' => 'utf8_general_ci',
  359. ],
  360. 'author_id' => [
  361. 'type' => 'integer',
  362. 'null' => false,
  363. 'unsigned' => false,
  364. 'default' => null,
  365. 'length' => null,
  366. 'precision' => null,
  367. 'comment' => null,
  368. 'autoIncrement' => null,
  369. ],
  370. 'published' => [
  371. 'type' => 'boolean',
  372. 'null' => true,
  373. 'default' => 0,
  374. 'length' => null,
  375. 'precision' => null,
  376. 'comment' => null,
  377. ],
  378. 'allow_comments' => [
  379. 'type' => 'boolean',
  380. 'null' => true,
  381. 'default' => 0,
  382. 'length' => null,
  383. 'precision' => null,
  384. 'comment' => null,
  385. ],
  386. 'created' => [
  387. 'type' => 'datetime',
  388. 'null' => true,
  389. 'default' => null,
  390. 'length' => null,
  391. 'precision' => null,
  392. 'comment' => null,
  393. ],
  394. 'created_with_precision' => [
  395. 'type' => 'datetimefractional',
  396. 'null' => true,
  397. 'default' => 'CURRENT_TIMESTAMP(3)',
  398. 'length' => null,
  399. 'precision' => 3,
  400. 'comment' => null,
  401. ],
  402. ];
  403. if (ConnectionManager::get('test')->getDriver()->isMariadb()) {
  404. $expected['created_with_precision']['default'] = 'current_timestamp(3)';
  405. $expected['created_with_precision']['comment'] = '';
  406. $expected['title']['collate'] = 'utf8mb3_general_ci';
  407. $expected['body']['collate'] = 'utf8mb3_general_ci';
  408. }
  409. $this->assertEquals(['id'], $result->getPrimaryKey());
  410. foreach ($expected as $field => $definition) {
  411. $this->assertEquals(
  412. $definition,
  413. $result->getColumn($field),
  414. 'Field definition does not match for ' . $field
  415. );
  416. }
  417. }
  418. /**
  419. * Test describing a table with indexes in MySQL
  420. */
  421. public function testDescribeTableIndexes(): void
  422. {
  423. $connection = ConnectionManager::get('test');
  424. $this->_createTables($connection);
  425. $schema = new SchemaCollection($connection);
  426. $result = $schema->describe('schema_articles');
  427. $this->assertInstanceOf('Cake\Database\Schema\TableSchema', $result);
  428. $this->assertCount(3, $result->constraints());
  429. $expected = [
  430. 'primary' => [
  431. 'type' => 'primary',
  432. 'columns' => ['id'],
  433. 'length' => [],
  434. ],
  435. 'length_idx' => [
  436. 'type' => 'unique',
  437. 'columns' => ['title'],
  438. 'length' => [
  439. 'title' => 4,
  440. ],
  441. ],
  442. 'schema_articles_ibfk_1' => [
  443. 'type' => 'foreign',
  444. 'columns' => ['author_id'],
  445. 'references' => ['schema_authors', 'id'],
  446. 'length' => [],
  447. 'update' => 'cascade',
  448. 'delete' => 'restrict',
  449. ],
  450. ];
  451. $this->assertEquals($expected['primary'], $result->getConstraint('primary'));
  452. $this->assertEquals($expected['length_idx'], $result->getConstraint('length_idx'));
  453. if (ConnectionManager::get('test')->getDriver()->isMariadb()) {
  454. $this->assertEquals($expected['schema_articles_ibfk_1'], $result->getConstraint('author_idx'));
  455. } else {
  456. $this->assertEquals($expected['schema_articles_ibfk_1'], $result->getConstraint('schema_articles_ibfk_1'));
  457. }
  458. $this->assertCount(1, $result->indexes());
  459. $expected = [
  460. 'type' => 'index',
  461. 'columns' => ['author_id'],
  462. 'length' => [],
  463. ];
  464. $this->assertEquals($expected, $result->getIndex('author_idx'));
  465. }
  466. /**
  467. * Test describing a table creates options
  468. */
  469. public function testDescribeTableOptions(): void
  470. {
  471. $connection = ConnectionManager::get('test');
  472. $this->_createTables($connection);
  473. $schema = new SchemaCollection($connection);
  474. $result = $schema->describe('schema_articles');
  475. $this->assertArrayHasKey('engine', $result->getOptions());
  476. $this->assertArrayHasKey('collation', $result->getOptions());
  477. }
  478. public function testDescribeNonPrimaryAutoIncrement(): void
  479. {
  480. $this->_needsConnection();
  481. $connection = ConnectionManager::get('test');
  482. $sql = <<<SQL
  483. CREATE TABLE `odd_primary_key` (
  484. `id` BIGINT UNSIGNED NOT NULL,
  485. `other_field` INTEGER NOT NULL AUTO_INCREMENT,
  486. PRIMARY KEY (`id`),
  487. UNIQUE KEY `other_field` (`other_field`)
  488. )
  489. SQL;
  490. $connection->execute($sql);
  491. $schema = new SchemaCollection($connection);
  492. $table = $schema->describe('odd_primary_key');
  493. $connection->execute('DROP TABLE odd_primary_key');
  494. $column = $table->getColumn('id');
  495. $this->assertNull($column['autoIncrement'], 'should not autoincrement');
  496. $this->assertTrue($column['unsigned'], 'should be unsigned');
  497. $column = $table->getColumn('other_field');
  498. $this->assertTrue($column['autoIncrement'], 'should not autoincrement');
  499. $this->assertFalse($column['unsigned'], 'should not be unsigned');
  500. $output = $table->createSql($connection);
  501. $this->assertStringContainsString('`id` BIGINT UNSIGNED NOT NULL,', $output[0]);
  502. $this->assertStringContainsString('`other_field` INTEGER NOT NULL AUTO_INCREMENT,', $output[0]);
  503. }
  504. /**
  505. * Column provider for creating column sql
  506. *
  507. * @return array
  508. */
  509. public static function columnSqlProvider(): array
  510. {
  511. return [
  512. // strings
  513. [
  514. 'title',
  515. ['type' => 'string', 'length' => 25, 'null' => true, 'default' => null],
  516. '`title` VARCHAR(25)',
  517. ],
  518. [
  519. 'title',
  520. ['type' => 'string', 'length' => 25, 'null' => false],
  521. '`title` VARCHAR(25) NOT NULL',
  522. ],
  523. [
  524. 'title',
  525. ['type' => 'string', 'length' => 25, 'null' => true, 'default' => 'ignored'],
  526. '`title` VARCHAR(25) DEFAULT \'ignored\'',
  527. ],
  528. [
  529. 'title',
  530. ['type' => 'string', 'length' => 25, 'null' => true, 'default' => ''],
  531. '`title` VARCHAR(25) DEFAULT \'\'',
  532. ],
  533. [
  534. 'role',
  535. ['type' => 'string', 'length' => 10, 'null' => false, 'default' => 'admin'],
  536. '`role` VARCHAR(10) NOT NULL DEFAULT \'admin\'',
  537. ],
  538. [
  539. 'id',
  540. ['type' => 'char', 'length' => 32, 'fixed' => true, 'null' => false],
  541. '`id` CHAR(32) NOT NULL',
  542. ],
  543. [
  544. 'title',
  545. ['type' => 'string'],
  546. '`title` VARCHAR(255)',
  547. ],
  548. [
  549. 'id',
  550. ['type' => 'uuid'],
  551. '`id` CHAR(36)',
  552. ],
  553. [
  554. 'id',
  555. ['type' => 'char', 'length' => 36],
  556. '`id` CHAR(36)',
  557. ],
  558. [
  559. 'id',
  560. ['type' => 'binaryuuid'],
  561. '`id` BINARY(16)',
  562. ],
  563. [
  564. 'title',
  565. ['type' => 'string', 'length' => 255, 'null' => false, 'collate' => 'utf8_unicode_ci'],
  566. '`title` VARCHAR(255) COLLATE utf8_unicode_ci NOT NULL',
  567. ],
  568. // Text
  569. [
  570. 'body',
  571. ['type' => 'text', 'null' => false],
  572. '`body` TEXT NOT NULL',
  573. ],
  574. [
  575. 'body',
  576. ['type' => 'text', 'length' => TableSchema::LENGTH_TINY, 'null' => false],
  577. '`body` TINYTEXT NOT NULL',
  578. ],
  579. [
  580. 'body',
  581. ['type' => 'text', 'length' => TableSchema::LENGTH_MEDIUM, 'null' => false],
  582. '`body` MEDIUMTEXT NOT NULL',
  583. ],
  584. [
  585. 'body',
  586. ['type' => 'text', 'length' => TableSchema::LENGTH_LONG, 'null' => false],
  587. '`body` LONGTEXT NOT NULL',
  588. ],
  589. [
  590. 'body',
  591. ['type' => 'text', 'null' => false, 'collate' => 'utf8_unicode_ci'],
  592. '`body` TEXT COLLATE utf8_unicode_ci NOT NULL',
  593. ],
  594. // Blob / binary
  595. [
  596. 'body',
  597. ['type' => 'binary', 'null' => false],
  598. '`body` BLOB NOT NULL',
  599. ],
  600. [
  601. 'body',
  602. ['type' => 'binary', 'length' => TableSchema::LENGTH_TINY, 'null' => false],
  603. '`body` TINYBLOB NOT NULL',
  604. ],
  605. [
  606. 'body',
  607. ['type' => 'binary', 'length' => TableSchema::LENGTH_MEDIUM, 'null' => false],
  608. '`body` MEDIUMBLOB NOT NULL',
  609. ],
  610. [
  611. 'body',
  612. ['type' => 'binary', 'length' => TableSchema::LENGTH_LONG, 'null' => false],
  613. '`body` LONGBLOB NOT NULL',
  614. ],
  615. [
  616. 'bytes',
  617. ['type' => 'binary', 'length' => 5],
  618. '`bytes` VARBINARY(5)',
  619. ],
  620. [
  621. 'bit',
  622. ['type' => 'binary', 'length' => 1],
  623. '`bit` BINARY(1)',
  624. ],
  625. // Integers
  626. [
  627. 'post_id',
  628. ['type' => 'tinyinteger'],
  629. '`post_id` TINYINT',
  630. ],
  631. [
  632. 'post_id',
  633. ['type' => 'tinyinteger', 'unsigned' => true],
  634. '`post_id` TINYINT UNSIGNED',
  635. ],
  636. [
  637. 'post_id',
  638. ['type' => 'smallinteger'],
  639. '`post_id` SMALLINT',
  640. ],
  641. [
  642. 'post_id',
  643. ['type' => 'smallinteger', 'unsigned' => true],
  644. '`post_id` SMALLINT UNSIGNED',
  645. ],
  646. [
  647. 'post_id',
  648. ['type' => 'integer'],
  649. '`post_id` INTEGER',
  650. ],
  651. [
  652. 'post_id',
  653. ['type' => 'integer', 'unsigned' => true],
  654. '`post_id` INTEGER UNSIGNED',
  655. ],
  656. [
  657. 'post_id',
  658. ['type' => 'biginteger'],
  659. '`post_id` BIGINT',
  660. ],
  661. [
  662. 'post_id',
  663. ['type' => 'biginteger', 'unsigned' => true],
  664. '`post_id` BIGINT UNSIGNED',
  665. ],
  666. [
  667. 'post_id',
  668. ['type' => 'integer', 'autoIncrement' => true],
  669. '`post_id` INTEGER AUTO_INCREMENT',
  670. ],
  671. [
  672. 'post_id',
  673. ['type' => 'integer', 'null' => false, 'autoIncrement' => false],
  674. '`post_id` INTEGER NOT NULL',
  675. ],
  676. [
  677. 'post_id',
  678. ['type' => 'biginteger', 'autoIncrement' => true],
  679. '`post_id` BIGINT AUTO_INCREMENT',
  680. ],
  681. // Decimal
  682. [
  683. 'value',
  684. ['type' => 'decimal'],
  685. '`value` DECIMAL',
  686. ],
  687. [
  688. 'value',
  689. ['type' => 'decimal', 'length' => 11, 'unsigned' => true],
  690. '`value` DECIMAL(11) UNSIGNED',
  691. ],
  692. [
  693. 'value',
  694. ['type' => 'decimal', 'length' => 12, 'precision' => 5],
  695. '`value` DECIMAL(12,5)',
  696. ],
  697. // Float
  698. [
  699. 'value',
  700. ['type' => 'float', 'unsigned'],
  701. '`value` FLOAT',
  702. ],
  703. [
  704. 'value',
  705. ['type' => 'float', 'unsigned' => true],
  706. '`value` FLOAT UNSIGNED',
  707. ],
  708. [
  709. 'latitude',
  710. ['type' => 'float', 'length' => 53, 'null' => true, 'default' => null, 'unsigned' => true],
  711. '`latitude` FLOAT(53) UNSIGNED',
  712. ],
  713. [
  714. 'value',
  715. ['type' => 'float', 'length' => 11, 'precision' => 3],
  716. '`value` FLOAT(11,3)',
  717. ],
  718. // Boolean
  719. [
  720. 'checked',
  721. ['type' => 'boolean', 'default' => false],
  722. '`checked` BOOLEAN DEFAULT FALSE',
  723. ],
  724. [
  725. 'checked',
  726. ['type' => 'boolean', 'default' => false, 'null' => false],
  727. '`checked` BOOLEAN NOT NULL DEFAULT FALSE',
  728. ],
  729. [
  730. 'checked',
  731. ['type' => 'boolean', 'default' => true, 'null' => false],
  732. '`checked` BOOLEAN NOT NULL DEFAULT TRUE',
  733. ],
  734. [
  735. 'checked',
  736. ['type' => 'boolean', 'default' => false, 'null' => true],
  737. '`checked` BOOLEAN DEFAULT FALSE',
  738. ],
  739. // datetimes
  740. [
  741. 'created',
  742. ['type' => 'datetime', 'comment' => 'Created timestamp'],
  743. '`created` DATETIME COMMENT \'Created timestamp\'',
  744. ],
  745. [
  746. 'created',
  747. ['type' => 'datetime', 'null' => false, 'default' => 'current_timestamp'],
  748. '`created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP',
  749. ],
  750. [
  751. 'open_date',
  752. ['type' => 'datetime', 'null' => false, 'default' => '2016-12-07 23:04:00'],
  753. '`open_date` DATETIME NOT NULL DEFAULT \'2016-12-07 23:04:00\'',
  754. ],
  755. [
  756. 'created_with_precision',
  757. ['type' => 'datetimefractional', 'precision' => 3, 'null' => false, 'default' => 'current_timestamp'],
  758. '`created_with_precision` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3)',
  759. ],
  760. // Date & Time
  761. [
  762. 'start_date',
  763. ['type' => 'date'],
  764. '`start_date` DATE',
  765. ],
  766. [
  767. 'start_time',
  768. ['type' => 'time'],
  769. '`start_time` TIME',
  770. ],
  771. // timestamps
  772. [
  773. 'created',
  774. ['type' => 'timestamp', 'null' => true],
  775. '`created` TIMESTAMP NULL',
  776. ],
  777. [
  778. 'created',
  779. ['type' => 'timestamp', 'null' => false, 'default' => 'current_timestamp'],
  780. '`created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP',
  781. ],
  782. [
  783. 'created',
  784. ['type' => 'timestamp', 'null' => false, 'default' => 'current_timestamp()'],
  785. '`created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP',
  786. ],
  787. [
  788. 'open_date',
  789. ['type' => 'timestamp', 'null' => false, 'default' => '2016-12-07 23:04:00'],
  790. '`open_date` TIMESTAMP NOT NULL DEFAULT \'2016-12-07 23:04:00\'',
  791. ],
  792. [
  793. 'created_with_precision',
  794. ['type' => 'timestampfractional', 'precision' => 3, 'null' => false, 'default' => 'current_timestamp'],
  795. '`created_with_precision` TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3)',
  796. ],
  797. ];
  798. }
  799. /**
  800. * Test generating column definitions
  801. *
  802. * @dataProvider columnSqlProvider
  803. */
  804. public function testColumnSql(string $name, array $data, string $expected): void
  805. {
  806. $driver = $this->_getMockedDriver();
  807. $schema = new MysqlSchemaDialect($driver);
  808. $table = (new TableSchema('articles'))->addColumn($name, $data);
  809. $this->assertEquals($expected, $schema->columnSql($table, $name));
  810. }
  811. /**
  812. * Provide data for testing constraintSql
  813. *
  814. * @return array
  815. */
  816. public static function constraintSqlProvider(): array
  817. {
  818. return [
  819. [
  820. 'primary',
  821. ['type' => 'primary', 'columns' => ['title']],
  822. 'PRIMARY KEY (`title`)',
  823. ],
  824. [
  825. 'unique_idx',
  826. ['type' => 'unique', 'columns' => ['title', 'author_id']],
  827. 'UNIQUE KEY `unique_idx` (`title`, `author_id`)',
  828. ],
  829. [
  830. 'length_idx',
  831. [
  832. 'type' => 'unique',
  833. 'columns' => ['author_id', 'title'],
  834. 'length' => ['author_id' => 5, 'title' => 4],
  835. ],
  836. 'UNIQUE KEY `length_idx` (`author_id`(5), `title`(4))',
  837. ],
  838. [
  839. 'author_id_idx',
  840. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id']],
  841. 'CONSTRAINT `author_id_idx` FOREIGN KEY (`author_id`) ' .
  842. 'REFERENCES `authors` (`id`) ON UPDATE RESTRICT ON DELETE RESTRICT',
  843. ],
  844. [
  845. 'author_id_idx',
  846. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'cascade'],
  847. 'CONSTRAINT `author_id_idx` FOREIGN KEY (`author_id`) ' .
  848. 'REFERENCES `authors` (`id`) ON UPDATE CASCADE ON DELETE RESTRICT',
  849. ],
  850. [
  851. 'author_id_idx',
  852. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'restrict'],
  853. 'CONSTRAINT `author_id_idx` FOREIGN KEY (`author_id`) ' .
  854. 'REFERENCES `authors` (`id`) ON UPDATE RESTRICT ON DELETE RESTRICT',
  855. ],
  856. [
  857. 'author_id_idx',
  858. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'setNull'],
  859. 'CONSTRAINT `author_id_idx` FOREIGN KEY (`author_id`) ' .
  860. 'REFERENCES `authors` (`id`) ON UPDATE SET NULL ON DELETE RESTRICT',
  861. ],
  862. [
  863. 'author_id_idx',
  864. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'noAction'],
  865. 'CONSTRAINT `author_id_idx` FOREIGN KEY (`author_id`) ' .
  866. 'REFERENCES `authors` (`id`) ON UPDATE NO ACTION ON DELETE RESTRICT',
  867. ],
  868. ];
  869. }
  870. /**
  871. * Test the constraintSql method.
  872. *
  873. * @dataProvider constraintSqlProvider
  874. */
  875. public function testConstraintSql(string $name, array $data, string $expected): void
  876. {
  877. $driver = $this->_getMockedDriver();
  878. $schema = new MysqlSchemaDialect($driver);
  879. $table = (new TableSchema('articles'))->addColumn('title', [
  880. 'type' => 'string',
  881. 'length' => 255,
  882. ])->addColumn('author_id', [
  883. 'type' => 'integer',
  884. ])->addConstraint($name, $data);
  885. $this->assertEquals($expected, $schema->constraintSql($table, $name));
  886. }
  887. /**
  888. * Test provider for indexSql()
  889. *
  890. * @return array
  891. */
  892. public static function indexSqlProvider(): array
  893. {
  894. return [
  895. [
  896. 'key_key',
  897. ['type' => 'index', 'columns' => ['author_id']],
  898. 'KEY `key_key` (`author_id`)',
  899. ],
  900. [
  901. 'full_text',
  902. ['type' => 'fulltext', 'columns' => ['title']],
  903. 'FULLTEXT KEY `full_text` (`title`)',
  904. ],
  905. ];
  906. }
  907. /**
  908. * Test the indexSql method.
  909. *
  910. * @dataProvider indexSqlProvider
  911. */
  912. public function testIndexSql(string $name, array $data, string $expected): void
  913. {
  914. $driver = $this->_getMockedDriver();
  915. $schema = new MysqlSchemaDialect($driver);
  916. $table = (new TableSchema('articles'))->addColumn('title', [
  917. 'type' => 'string',
  918. 'length' => 255,
  919. ])->addColumn('author_id', [
  920. 'type' => 'integer',
  921. ])->addIndex($name, $data);
  922. $this->assertEquals($expected, $schema->indexSql($table, $name));
  923. }
  924. /**
  925. * Test the addConstraintSql method.
  926. */
  927. public function testAddConstraintSql(): void
  928. {
  929. $driver = $this->_getMockedDriver();
  930. $connection = $this->getMockBuilder('Cake\Database\Connection')
  931. ->disableOriginalConstructor()
  932. ->getMock();
  933. $connection->expects($this->any())->method('getDriver')
  934. ->will($this->returnValue($driver));
  935. $table = (new TableSchema('posts'))
  936. ->addColumn('author_id', [
  937. 'type' => 'integer',
  938. 'null' => false,
  939. ])
  940. ->addColumn('category_id', [
  941. 'type' => 'integer',
  942. 'null' => false,
  943. ])
  944. ->addColumn('category_name', [
  945. 'type' => 'integer',
  946. 'null' => false,
  947. ])
  948. ->addConstraint('author_fk', [
  949. 'type' => 'foreign',
  950. 'columns' => ['author_id'],
  951. 'references' => ['authors', 'id'],
  952. 'update' => 'cascade',
  953. 'delete' => 'cascade',
  954. ])
  955. ->addConstraint('category_fk', [
  956. 'type' => 'foreign',
  957. 'columns' => ['category_id', 'category_name'],
  958. 'references' => ['categories', ['id', 'name']],
  959. 'update' => 'cascade',
  960. 'delete' => 'cascade',
  961. ]);
  962. $expected = [
  963. 'ALTER TABLE `posts` ADD CONSTRAINT `author_fk` FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`) ON UPDATE CASCADE ON DELETE CASCADE;',
  964. 'ALTER TABLE `posts` ADD CONSTRAINT `category_fk` FOREIGN KEY (`category_id`, `category_name`) REFERENCES `categories` (`id`, `name`) ON UPDATE CASCADE ON DELETE CASCADE;',
  965. ];
  966. $result = $table->addConstraintSql($connection);
  967. $this->assertCount(2, $result);
  968. $this->assertEquals($expected, $result);
  969. }
  970. /**
  971. * Test the dropConstraintSql method.
  972. */
  973. public function testDropConstraintSql(): void
  974. {
  975. $driver = $this->_getMockedDriver();
  976. $connection = $this->getMockBuilder('Cake\Database\Connection')
  977. ->disableOriginalConstructor()
  978. ->getMock();
  979. $connection->expects($this->any())->method('getDriver')
  980. ->will($this->returnValue($driver));
  981. $table = (new TableSchema('posts'))
  982. ->addColumn('author_id', [
  983. 'type' => 'integer',
  984. 'null' => false,
  985. ])
  986. ->addColumn('category_id', [
  987. 'type' => 'integer',
  988. 'null' => false,
  989. ])
  990. ->addColumn('category_name', [
  991. 'type' => 'integer',
  992. 'null' => false,
  993. ])
  994. ->addConstraint('author_fk', [
  995. 'type' => 'foreign',
  996. 'columns' => ['author_id'],
  997. 'references' => ['authors', 'id'],
  998. 'update' => 'cascade',
  999. 'delete' => 'cascade',
  1000. ])
  1001. ->addConstraint('category_fk', [
  1002. 'type' => 'foreign',
  1003. 'columns' => ['category_id', 'category_name'],
  1004. 'references' => ['categories', ['id', 'name']],
  1005. 'update' => 'cascade',
  1006. 'delete' => 'cascade',
  1007. ]);
  1008. $expected = [
  1009. 'ALTER TABLE `posts` DROP FOREIGN KEY `author_fk`;',
  1010. 'ALTER TABLE `posts` DROP FOREIGN KEY `category_fk`;',
  1011. ];
  1012. $result = $table->dropConstraintSql($connection);
  1013. $this->assertCount(2, $result);
  1014. $this->assertEquals($expected, $result);
  1015. }
  1016. /**
  1017. * Test generating a column that is a primary key.
  1018. */
  1019. public function testColumnSqlPrimaryKey(): void
  1020. {
  1021. $driver = $this->_getMockedDriver();
  1022. $schema = new MysqlSchemaDialect($driver);
  1023. $table = new TableSchema('articles');
  1024. $table->addColumn('id', [
  1025. 'type' => 'integer',
  1026. 'null' => false,
  1027. ])
  1028. ->addConstraint('primary', [
  1029. 'type' => 'primary',
  1030. 'columns' => ['id'],
  1031. ]);
  1032. $result = $schema->columnSql($table, 'id');
  1033. $this->assertSame($result, '`id` INTEGER NOT NULL AUTO_INCREMENT');
  1034. $table = new TableSchema('articles');
  1035. $table->addColumn('id', [
  1036. 'type' => 'biginteger',
  1037. 'null' => false,
  1038. ])
  1039. ->addConstraint('primary', [
  1040. 'type' => 'primary',
  1041. 'columns' => ['id'],
  1042. ]);
  1043. $result = $schema->columnSql($table, 'id');
  1044. $this->assertSame($result, '`id` BIGINT NOT NULL AUTO_INCREMENT');
  1045. }
  1046. /**
  1047. * Integration test for converting a Schema\Table into MySQL table creates.
  1048. */
  1049. public function testCreateSql(): void
  1050. {
  1051. $driver = $this->_getMockedDriver();
  1052. $connection = $this->getMockBuilder('Cake\Database\Connection')
  1053. ->disableOriginalConstructor()
  1054. ->getMock();
  1055. $connection->expects($this->any())->method('getDriver')
  1056. ->will($this->returnValue($driver));
  1057. $driver->getConnection()
  1058. ->expects($this->any())
  1059. ->method('getAttribute')
  1060. ->will($this->returnValue('5.6.0'));
  1061. $table = (new TableSchema('posts'))->addColumn('id', [
  1062. 'type' => 'integer',
  1063. 'null' => false,
  1064. ])
  1065. ->addColumn('title', [
  1066. 'type' => 'string',
  1067. 'null' => false,
  1068. 'comment' => 'The title',
  1069. ])
  1070. ->addColumn('body', [
  1071. 'type' => 'text',
  1072. 'comment' => '',
  1073. ])
  1074. ->addColumn('data', [
  1075. 'type' => 'json',
  1076. ])
  1077. ->addColumn('hash', [
  1078. 'type' => 'char',
  1079. 'fixed' => true,
  1080. 'length' => 40,
  1081. 'collate' => 'latin1_bin',
  1082. 'null' => false,
  1083. ])
  1084. ->addColumn('created', 'datetime')
  1085. ->addConstraint('primary', [
  1086. 'type' => 'primary',
  1087. 'columns' => ['id'],
  1088. ])
  1089. ->setOptions([
  1090. 'engine' => 'InnoDB',
  1091. 'charset' => 'utf8',
  1092. 'collate' => 'utf8_general_ci',
  1093. ]);
  1094. $expected = <<<SQL
  1095. CREATE TABLE `posts` (
  1096. `id` INTEGER NOT NULL AUTO_INCREMENT,
  1097. `title` VARCHAR(255) NOT NULL COMMENT 'The title',
  1098. `body` TEXT,
  1099. `data` LONGTEXT,
  1100. `hash` CHAR(40) COLLATE latin1_bin NOT NULL,
  1101. `created` DATETIME,
  1102. PRIMARY KEY (`id`)
  1103. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci
  1104. SQL;
  1105. $result = $table->createSql($connection);
  1106. $this->assertCount(1, $result);
  1107. $this->assertTextEquals($expected, $result[0]);
  1108. }
  1109. /**
  1110. * Integration test for converting a Schema\Table with native JSON
  1111. */
  1112. public function testCreateSqlJson(): void
  1113. {
  1114. $driver = $this->_getMockedDriver();
  1115. $connection = $this->getMockBuilder('Cake\Database\Connection')
  1116. ->disableOriginalConstructor()
  1117. ->getMock();
  1118. $connection->expects($this->any())
  1119. ->method('getDriver')
  1120. ->will($this->returnValue($driver));
  1121. $driver->getConnection()
  1122. ->expects($this->any())
  1123. ->method('getAttribute')
  1124. ->will($this->returnValue('5.7.0'));
  1125. $table = (new TableSchema('posts'))->addColumn('id', [
  1126. 'type' => 'integer',
  1127. 'null' => false,
  1128. ])
  1129. ->addColumn('data', [
  1130. 'type' => 'json',
  1131. ])
  1132. ->addConstraint('primary', [
  1133. 'type' => 'primary',
  1134. 'columns' => ['id'],
  1135. ])
  1136. ->setOptions([
  1137. 'engine' => 'InnoDB',
  1138. 'charset' => 'utf8',
  1139. 'collate' => 'utf8_general_ci',
  1140. ]);
  1141. $expected = <<<SQL
  1142. CREATE TABLE `posts` (
  1143. `id` INTEGER NOT NULL AUTO_INCREMENT,
  1144. `data` JSON,
  1145. PRIMARY KEY (`id`)
  1146. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci
  1147. SQL;
  1148. $result = $table->createSql($connection);
  1149. $this->assertCount(1, $result);
  1150. $this->assertTextEquals($expected, $result[0]);
  1151. }
  1152. /**
  1153. * Tests creating temporary tables
  1154. */
  1155. public function testCreateTemporary(): void
  1156. {
  1157. $driver = $this->_getMockedDriver();
  1158. $connection = $this->getMockBuilder('Cake\Database\Connection')
  1159. ->disableOriginalConstructor()
  1160. ->getMock();
  1161. $connection->expects($this->any())->method('getDriver')
  1162. ->will($this->returnValue($driver));
  1163. $table = (new TableSchema('schema_articles'))->addColumn('id', [
  1164. 'type' => 'integer',
  1165. 'null' => false,
  1166. ]);
  1167. $table->setTemporary(true);
  1168. $sql = $table->createSql($connection);
  1169. $this->assertStringContainsString('CREATE TEMPORARY TABLE', $sql[0]);
  1170. }
  1171. /**
  1172. * Test primary key generation & auto-increment.
  1173. */
  1174. public function testCreateSqlCompositeIntegerKey(): void
  1175. {
  1176. $driver = $this->_getMockedDriver();
  1177. $connection = $this->getMockBuilder('Cake\Database\Connection')
  1178. ->disableOriginalConstructor()
  1179. ->getMock();
  1180. $connection->expects($this->any())->method('getDriver')
  1181. ->will($this->returnValue($driver));
  1182. $table = (new TableSchema('articles_tags'))
  1183. ->addColumn('article_id', [
  1184. 'type' => 'integer',
  1185. 'null' => false,
  1186. ])
  1187. ->addColumn('tag_id', [
  1188. 'type' => 'integer',
  1189. 'null' => false,
  1190. ])
  1191. ->addConstraint('primary', [
  1192. 'type' => 'primary',
  1193. 'columns' => ['article_id', 'tag_id'],
  1194. ]);
  1195. $expected = <<<SQL
  1196. CREATE TABLE `articles_tags` (
  1197. `article_id` INTEGER NOT NULL,
  1198. `tag_id` INTEGER NOT NULL,
  1199. PRIMARY KEY (`article_id`, `tag_id`)
  1200. )
  1201. SQL;
  1202. $result = $table->createSql($connection);
  1203. $this->assertCount(1, $result);
  1204. $this->assertTextEquals($expected, $result[0]);
  1205. $table = (new TableSchema('composite_key'))
  1206. ->addColumn('id', [
  1207. 'type' => 'integer',
  1208. 'null' => false,
  1209. 'autoIncrement' => true,
  1210. ])
  1211. ->addColumn('account_id', [
  1212. 'type' => 'integer',
  1213. 'null' => false,
  1214. ])
  1215. ->addConstraint('primary', [
  1216. 'type' => 'primary',
  1217. 'columns' => ['id', 'account_id'],
  1218. ]);
  1219. $expected = <<<SQL
  1220. CREATE TABLE `composite_key` (
  1221. `id` INTEGER NOT NULL AUTO_INCREMENT,
  1222. `account_id` INTEGER NOT NULL,
  1223. PRIMARY KEY (`id`, `account_id`)
  1224. )
  1225. SQL;
  1226. $result = $table->createSql($connection);
  1227. $this->assertCount(1, $result);
  1228. $this->assertTextEquals($expected, $result[0]);
  1229. }
  1230. /**
  1231. * test dropSql
  1232. */
  1233. public function testDropSql(): void
  1234. {
  1235. $driver = $this->_getMockedDriver();
  1236. $connection = $this->getMockBuilder('Cake\Database\Connection')
  1237. ->disableOriginalConstructor()
  1238. ->getMock();
  1239. $connection->expects($this->any())->method('getDriver')
  1240. ->will($this->returnValue($driver));
  1241. $table = new TableSchema('articles');
  1242. $result = $table->dropSql($connection);
  1243. $this->assertCount(1, $result);
  1244. $this->assertSame('DROP TABLE `articles`', $result[0]);
  1245. }
  1246. /**
  1247. * Test truncateSql()
  1248. */
  1249. public function testTruncateSql(): void
  1250. {
  1251. $driver = $this->_getMockedDriver();
  1252. $connection = $this->getMockBuilder('Cake\Database\Connection')
  1253. ->disableOriginalConstructor()
  1254. ->getMock();
  1255. $connection->expects($this->any())->method('getDriver')
  1256. ->will($this->returnValue($driver));
  1257. $table = new TableSchema('articles');
  1258. $result = $table->truncateSql($connection);
  1259. $this->assertCount(1, $result);
  1260. $this->assertSame('TRUNCATE TABLE `articles`', $result[0]);
  1261. }
  1262. /**
  1263. * Test that constructing a schema dialect connects the driver.
  1264. */
  1265. public function testConstructConnectsDriver(): void
  1266. {
  1267. $driver = $this->getMockBuilder('Cake\Database\Driver')->getMock();
  1268. $driver->expects($this->once())
  1269. ->method('connect');
  1270. $schema = new MysqlSchemaDialect($driver);
  1271. }
  1272. /**
  1273. * Tests JSON column parsing on MySQL 5.7+
  1274. */
  1275. public function testDescribeJson(): void
  1276. {
  1277. $connection = ConnectionManager::get('test');
  1278. $this->_createTables($connection);
  1279. $this->skipIf(!$connection->getDriver()->supports(DriverInterface::FEATURE_JSON), 'Does not support native json');
  1280. $this->skipIf($connection->getDriver()->isMariadb(), 'MariaDb internally uses TEXT for JSON columns');
  1281. $schema = new SchemaCollection($connection);
  1282. $result = $schema->describe('schema_json');
  1283. $this->assertInstanceOf('Cake\Database\Schema\TableSchema', $result);
  1284. $expected = [
  1285. 'type' => 'json',
  1286. 'null' => false,
  1287. 'default' => null,
  1288. 'length' => null,
  1289. 'precision' => null,
  1290. 'comment' => null,
  1291. ];
  1292. $this->assertEquals(
  1293. $expected,
  1294. $result->getColumn('data'),
  1295. 'Field definition does not match for data'
  1296. );
  1297. }
  1298. /**
  1299. * Get a schema instance with a mocked driver/pdo instances
  1300. */
  1301. protected function _getMockedDriver(): Driver
  1302. {
  1303. $driver = new Mysql();
  1304. $mock = $this->getMockBuilder(PDO::class)
  1305. ->onlyMethods(['quote', 'getAttribute'])
  1306. ->addMethods(['quoteIdentifier'])
  1307. ->disableOriginalConstructor()
  1308. ->getMock();
  1309. $mock->expects($this->any())
  1310. ->method('quote')
  1311. ->will($this->returnCallback(function ($value) {
  1312. return "'$value'";
  1313. }));
  1314. $driver->setConnection($mock);
  1315. return $driver;
  1316. }
  1317. }