PostgresSchemaTest.php 42 KB

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