PostgresSchemaTest.php 38 KB

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