PostgresSchemaTest.php 40 KB

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