MysqlSchemaTest.php 48 KB

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