PostgresSchemaTest.php 42 KB

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