PostgresSchemaTest.php 40 KB

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