PostgresSchemaTest.php 47 KB

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