PostgresSchemaTest.php 40 KB

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