PostgresSchemaTest.php 39 KB

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