MysqlSchemaTest.php 51 KB

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