PostgresSchemaTest.php 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  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. average_note DECIMAL(4,2),
  72. average_income NUMERIC(10,2),
  73. created TIMESTAMP,
  74. CONSTRAINT "content_idx" UNIQUE ("title", "body"),
  75. CONSTRAINT "author_idx" FOREIGN KEY ("author_id") REFERENCES "schema_authors" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
  76. )
  77. SQL;
  78. $connection->execute($table);
  79. $connection->execute('COMMENT ON COLUMN "schema_articles"."title" IS \'a title\'');
  80. $connection->execute('CREATE INDEX "author_idx" ON "schema_articles" ("author_id")');
  81. }
  82. /**
  83. * Data provider for convert column testing
  84. *
  85. * @return array
  86. */
  87. public static function convertColumnProvider()
  88. {
  89. return [
  90. // Timestamp
  91. [
  92. 'TIMESTAMP',
  93. ['type' => 'timestamp', 'length' => null]
  94. ],
  95. [
  96. 'TIMESTAMP WITHOUT TIME ZONE',
  97. ['type' => 'timestamp', 'length' => null]
  98. ],
  99. // Date & time
  100. [
  101. 'DATE',
  102. ['type' => 'date', 'length' => null]
  103. ],
  104. [
  105. 'TIME',
  106. ['type' => 'time', 'length' => null]
  107. ],
  108. [
  109. 'TIME WITHOUT TIME ZONE',
  110. ['type' => 'time', 'length' => null]
  111. ],
  112. // Integer
  113. [
  114. 'SMALLINT',
  115. ['type' => 'integer', 'length' => 5]
  116. ],
  117. [
  118. 'INTEGER',
  119. ['type' => 'integer', 'length' => 10]
  120. ],
  121. [
  122. 'SERIAL',
  123. ['type' => 'integer', 'length' => 10]
  124. ],
  125. [
  126. 'BIGINT',
  127. ['type' => 'biginteger', 'length' => 20]
  128. ],
  129. [
  130. 'BIGSERIAL',
  131. ['type' => 'biginteger', 'length' => 20]
  132. ],
  133. // Decimal
  134. [
  135. 'NUMERIC',
  136. ['type' => 'decimal', 'length' => null, 'precision' => null]
  137. ],
  138. [
  139. 'DECIMAL(10,2)',
  140. ['type' => 'decimal', 'length' => 10, 'precision' => 2]
  141. ],
  142. // String
  143. [
  144. 'VARCHAR',
  145. ['type' => 'string', 'length' => null]
  146. ],
  147. [
  148. 'VARCHAR(10)',
  149. ['type' => 'string', 'length' => 10]
  150. ],
  151. [
  152. 'CHARACTER VARYING',
  153. ['type' => 'string', 'length' => null]
  154. ],
  155. [
  156. 'CHARACTER VARYING(10)',
  157. ['type' => 'string', 'length' => 10]
  158. ],
  159. [
  160. 'CHAR(10)',
  161. ['type' => 'string', 'fixed' => true, 'length' => 10]
  162. ],
  163. [
  164. 'CHARACTER(10)',
  165. ['type' => 'string', 'fixed' => true, 'length' => 10]
  166. ],
  167. [
  168. 'MONEY',
  169. ['type' => 'string', 'length' => null]
  170. ],
  171. // UUID
  172. [
  173. 'UUID',
  174. ['type' => 'uuid', 'length' => null]
  175. ],
  176. [
  177. 'INET',
  178. ['type' => 'string', 'length' => 39]
  179. ],
  180. // Text
  181. [
  182. 'TEXT',
  183. ['type' => 'text', 'length' => null]
  184. ],
  185. // Blob
  186. [
  187. 'BYTEA',
  188. ['type' => 'binary', 'length' => null]
  189. ],
  190. // Float
  191. [
  192. 'REAL',
  193. ['type' => 'float', 'length' => null]
  194. ],
  195. [
  196. 'DOUBLE PRECISION',
  197. ['type' => 'float', 'length' => null]
  198. ],
  199. [
  200. 'JSON',
  201. ['type' => 'json', 'length' => null]
  202. ],
  203. [
  204. 'JSONB',
  205. ['type' => 'json', 'length' => null]
  206. ],
  207. ];
  208. }
  209. /**
  210. * Test parsing Postgres column types from field description.
  211. *
  212. * @dataProvider convertColumnProvider
  213. * @return void
  214. */
  215. public function testConvertColumn($type, $expected)
  216. {
  217. $field = [
  218. 'name' => 'field',
  219. 'type' => $type,
  220. 'null' => 'YES',
  221. 'default' => 'Default value',
  222. 'comment' => 'Comment section',
  223. 'char_length' => null,
  224. 'column_precision' => null,
  225. 'column_scale' => null,
  226. 'collation_name' => 'ja_JP.utf8',
  227. ];
  228. $expected += [
  229. 'null' => true,
  230. 'default' => 'Default value',
  231. 'comment' => 'Comment section',
  232. 'collate' => 'ja_JP.utf8',
  233. ];
  234. if ($field['type'] === 'NUMERIC' || strpos($field['type'], 'DECIMAL') !== false) {
  235. $field['column_precision'] = $expected['length'];
  236. $field['column_scale'] = $expected['precision'];
  237. }
  238. $driver = $this->getMockBuilder('Cake\Database\Driver\Postgres')->getMock();
  239. $dialect = new PostgresSchema($driver);
  240. $table = $this->getMockBuilder('Cake\Database\Schema\Table')
  241. ->setConstructorArgs(['table'])
  242. ->getMock();
  243. $table->expects($this->at(0))->method('addColumn')->with('field', $expected);
  244. $dialect->convertColumnDescription($table, $field);
  245. }
  246. /**
  247. * Test listing tables with Postgres
  248. *
  249. * @return void
  250. */
  251. public function testListTables()
  252. {
  253. $connection = ConnectionManager::get('test');
  254. $this->_createTables($connection);
  255. $schema = new SchemaCollection($connection);
  256. $result = $schema->listTables();
  257. $this->assertInternalType('array', $result);
  258. $this->assertContains('schema_articles', $result);
  259. $this->assertContains('schema_authors', $result);
  260. }
  261. /**
  262. * Test that describe accepts tablenames containing `schema.table`.
  263. *
  264. * @return void
  265. */
  266. public function testDescribeWithSchemaName()
  267. {
  268. $connection = ConnectionManager::get('test');
  269. $this->_createTables($connection);
  270. $schema = new SchemaCollection($connection);
  271. $result = $schema->describe('public.schema_articles');
  272. $this->assertEquals(['id'], $result->primaryKey());
  273. $this->assertEquals('schema_articles', $result->name());
  274. }
  275. /**
  276. * Test describing a table with Postgres
  277. *
  278. * @return void
  279. */
  280. public function testDescribeTable()
  281. {
  282. $connection = ConnectionManager::get('test');
  283. $this->_createTables($connection);
  284. $schema = new SchemaCollection($connection);
  285. $result = $schema->describe('schema_articles');
  286. $expected = [
  287. 'id' => [
  288. 'type' => 'biginteger',
  289. 'null' => false,
  290. 'default' => null,
  291. 'length' => 20,
  292. 'precision' => null,
  293. 'unsigned' => null,
  294. 'comment' => null,
  295. 'autoIncrement' => false,
  296. ],
  297. 'title' => [
  298. 'type' => 'string',
  299. 'null' => true,
  300. 'default' => null,
  301. 'length' => 20,
  302. 'precision' => null,
  303. 'comment' => 'a title',
  304. 'fixed' => null,
  305. 'collate' => null,
  306. ],
  307. 'body' => [
  308. 'type' => 'text',
  309. 'null' => true,
  310. 'default' => null,
  311. 'length' => null,
  312. 'precision' => null,
  313. 'comment' => null,
  314. 'collate' => null,
  315. ],
  316. 'author_id' => [
  317. 'type' => 'integer',
  318. 'null' => false,
  319. 'default' => null,
  320. 'length' => 10,
  321. 'precision' => null,
  322. 'unsigned' => null,
  323. 'comment' => null,
  324. 'autoIncrement' => null,
  325. ],
  326. 'published' => [
  327. 'type' => 'boolean',
  328. 'null' => true,
  329. 'default' => 0,
  330. 'length' => null,
  331. 'precision' => null,
  332. 'comment' => null,
  333. ],
  334. 'views' => [
  335. 'type' => 'integer',
  336. 'null' => true,
  337. 'default' => 0,
  338. 'length' => 5,
  339. 'precision' => null,
  340. 'unsigned' => null,
  341. 'comment' => null,
  342. 'autoIncrement' => 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' => Table::LENGTH_TINY, 'null' => false],
  658. sprintf('"body" VARCHAR(%s) NOT NULL', Table::LENGTH_TINY)
  659. ],
  660. [
  661. 'body',
  662. ['type' => 'text', 'length' => Table::LENGTH_MEDIUM, 'null' => false],
  663. '"body" TEXT NOT NULL'
  664. ],
  665. [
  666. 'body',
  667. ['type' => 'text', 'length' => Table::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' => 'integer', 'length' => 11],
  679. '"post_id" INTEGER'
  680. ],
  681. [
  682. 'post_id',
  683. ['type' => 'biginteger', 'length' => 20],
  684. '"post_id" BIGINT'
  685. ],
  686. [
  687. 'post_id',
  688. ['type' => 'integer', 'autoIncrement' => true, 'length' => 11],
  689. '"post_id" SERIAL'
  690. ],
  691. [
  692. 'post_id',
  693. ['type' => 'biginteger', 'autoIncrement' => true, 'length' => 20],
  694. '"post_id" BIGSERIAL'
  695. ],
  696. // Decimal
  697. [
  698. 'value',
  699. ['type' => 'decimal'],
  700. '"value" DECIMAL'
  701. ],
  702. [
  703. 'value',
  704. ['type' => 'decimal', 'length' => 11],
  705. '"value" DECIMAL(11,0)'
  706. ],
  707. [
  708. 'value',
  709. ['type' => 'decimal', 'length' => 12, 'precision' => 5],
  710. '"value" DECIMAL(12,5)'
  711. ],
  712. // Float
  713. [
  714. 'value',
  715. ['type' => 'float'],
  716. '"value" FLOAT'
  717. ],
  718. [
  719. 'value',
  720. ['type' => 'float', 'length' => 11, 'precision' => 3],
  721. '"value" FLOAT(3)'
  722. ],
  723. // Binary
  724. [
  725. 'img',
  726. ['type' => 'binary'],
  727. '"img" BYTEA'
  728. ],
  729. // Boolean
  730. [
  731. 'checked',
  732. ['type' => 'boolean', 'default' => false],
  733. '"checked" BOOLEAN DEFAULT FALSE'
  734. ],
  735. [
  736. 'checked',
  737. ['type' => 'boolean', 'default' => true, 'null' => false],
  738. '"checked" BOOLEAN NOT NULL DEFAULT TRUE'
  739. ],
  740. // Boolean
  741. [
  742. 'checked',
  743. ['type' => 'boolean', 'default' => 0],
  744. '"checked" BOOLEAN DEFAULT FALSE'
  745. ],
  746. [
  747. 'checked',
  748. ['type' => 'boolean', 'default' => 1, 'null' => false],
  749. '"checked" BOOLEAN NOT NULL DEFAULT TRUE'
  750. ],
  751. // Datetime
  752. [
  753. 'created',
  754. ['type' => 'datetime'],
  755. '"created" TIMESTAMP'
  756. ],
  757. [
  758. 'open_date',
  759. ['type' => 'datetime', 'null' => false, 'default' => '2016-12-07 23:04:00'],
  760. '"open_date" TIMESTAMP NOT NULL DEFAULT \'2016-12-07 23:04:00\''
  761. ],
  762. [
  763. 'null_date',
  764. ['type' => 'datetime', 'null' => true],
  765. '"null_date" TIMESTAMP NULL DEFAULT NULL'
  766. ],
  767. [
  768. 'current_timestamp',
  769. ['type' => 'datetime', 'null' => false, 'default' => 'CURRENT_TIMESTAMP'],
  770. '"current_timestamp" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP'
  771. ],
  772. // Date & Time
  773. [
  774. 'start_date',
  775. ['type' => 'date'],
  776. '"start_date" DATE'
  777. ],
  778. [
  779. 'start_time',
  780. ['type' => 'time'],
  781. '"start_time" TIME'
  782. ],
  783. // Timestamp
  784. [
  785. 'created',
  786. ['type' => 'timestamp', 'null' => true],
  787. '"created" TIMESTAMP DEFAULT NULL'
  788. ],
  789. ];
  790. }
  791. /**
  792. * Test generating column definitions
  793. *
  794. * @dataProvider columnSqlProvider
  795. * @return void
  796. */
  797. public function testColumnSql($name, $data, $expected)
  798. {
  799. $driver = $this->_getMockedDriver();
  800. $schema = new PostgresSchema($driver);
  801. $table = (new Table('schema_articles'))->addColumn($name, $data);
  802. $this->assertEquals($expected, $schema->columnSql($table, $name));
  803. }
  804. /**
  805. * Test generating a column that is a primary key.
  806. *
  807. * @return void
  808. */
  809. public function testColumnSqlPrimaryKey()
  810. {
  811. $driver = $this->_getMockedDriver();
  812. $schema = new PostgresSchema($driver);
  813. $table = new Table('schema_articles');
  814. $table->addColumn('id', [
  815. 'type' => 'integer',
  816. 'null' => false
  817. ])
  818. ->addConstraint('primary', [
  819. 'type' => 'primary',
  820. 'columns' => ['id']
  821. ]);
  822. $result = $schema->columnSql($table, 'id');
  823. $this->assertEquals($result, '"id" SERIAL');
  824. }
  825. /**
  826. * Provide data for testing constraintSql
  827. *
  828. * @return array
  829. */
  830. public static function constraintSqlProvider()
  831. {
  832. return [
  833. [
  834. 'primary',
  835. ['type' => 'primary', 'columns' => ['title']],
  836. 'PRIMARY KEY ("title")'
  837. ],
  838. [
  839. 'unique_idx',
  840. ['type' => 'unique', 'columns' => ['title', 'author_id']],
  841. 'CONSTRAINT "unique_idx" UNIQUE ("title", "author_id")'
  842. ],
  843. [
  844. 'author_id_idx',
  845. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id']],
  846. 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
  847. 'REFERENCES "authors" ("id") ON UPDATE RESTRICT ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE'
  848. ],
  849. [
  850. 'author_id_idx',
  851. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'cascade'],
  852. 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
  853. 'REFERENCES "authors" ("id") ON UPDATE CASCADE ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE'
  854. ],
  855. [
  856. 'author_id_idx',
  857. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'restrict'],
  858. 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
  859. 'REFERENCES "authors" ("id") ON UPDATE RESTRICT ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE'
  860. ],
  861. [
  862. 'author_id_idx',
  863. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'setNull'],
  864. 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
  865. 'REFERENCES "authors" ("id") ON UPDATE SET NULL ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE'
  866. ],
  867. [
  868. 'author_id_idx',
  869. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'noAction'],
  870. 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
  871. 'REFERENCES "authors" ("id") ON UPDATE NO ACTION ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE'
  872. ],
  873. ];
  874. }
  875. /**
  876. * Test the constraintSql method.
  877. *
  878. * @dataProvider constraintSqlProvider
  879. */
  880. public function testConstraintSql($name, $data, $expected)
  881. {
  882. $driver = $this->_getMockedDriver();
  883. $schema = new PostgresSchema($driver);
  884. $table = (new Table('schema_articles'))->addColumn('title', [
  885. 'type' => 'string',
  886. 'length' => 255
  887. ])->addColumn('author_id', [
  888. 'type' => 'integer',
  889. ])->addConstraint($name, $data);
  890. $this->assertTextEquals($expected, $schema->constraintSql($table, $name));
  891. }
  892. /**
  893. * Test the addConstraintSql method.
  894. *
  895. * @return void
  896. */
  897. public function testAddConstraintSql()
  898. {
  899. $driver = $this->_getMockedDriver();
  900. $connection = $this->getMockBuilder('Cake\Database\Connection')
  901. ->disableOriginalConstructor()
  902. ->getMock();
  903. $connection->expects($this->any())->method('driver')
  904. ->will($this->returnValue($driver));
  905. $table = (new Table('posts'))
  906. ->addColumn('author_id', [
  907. 'type' => 'integer',
  908. 'null' => false
  909. ])
  910. ->addColumn('category_id', [
  911. 'type' => 'integer',
  912. 'null' => false
  913. ])
  914. ->addColumn('category_name', [
  915. 'type' => 'integer',
  916. 'null' => false
  917. ])
  918. ->addConstraint('author_fk', [
  919. 'type' => 'foreign',
  920. 'columns' => ['author_id'],
  921. 'references' => ['authors', 'id'],
  922. 'update' => 'cascade',
  923. 'delete' => 'cascade'
  924. ])
  925. ->addConstraint('category_fk', [
  926. 'type' => 'foreign',
  927. 'columns' => ['category_id', 'category_name'],
  928. 'references' => ['categories', ['id', 'name']],
  929. 'update' => 'cascade',
  930. 'delete' => 'cascade'
  931. ]);
  932. $expected = [
  933. 'ALTER TABLE "posts" ADD CONSTRAINT "author_fk" FOREIGN KEY ("author_id") REFERENCES "authors" ("id") ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY IMMEDIATE;',
  934. '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;'
  935. ];
  936. $result = $table->addConstraintSql($connection);
  937. $this->assertCount(2, $result);
  938. $this->assertEquals($expected, $result);
  939. }
  940. /**
  941. * Test the dropConstraintSql method.
  942. *
  943. * @return void
  944. */
  945. public function testDropConstraintSql()
  946. {
  947. $driver = $this->_getMockedDriver();
  948. $connection = $this->getMockBuilder('Cake\Database\Connection')
  949. ->disableOriginalConstructor()
  950. ->getMock();
  951. $connection->expects($this->any())->method('driver')
  952. ->will($this->returnValue($driver));
  953. $table = (new Table('posts'))
  954. ->addColumn('author_id', [
  955. 'type' => 'integer',
  956. 'null' => false
  957. ])
  958. ->addColumn('category_id', [
  959. 'type' => 'integer',
  960. 'null' => false
  961. ])
  962. ->addColumn('category_name', [
  963. 'type' => 'integer',
  964. 'null' => false
  965. ])
  966. ->addConstraint('author_fk', [
  967. 'type' => 'foreign',
  968. 'columns' => ['author_id'],
  969. 'references' => ['authors', 'id'],
  970. 'update' => 'cascade',
  971. 'delete' => 'cascade'
  972. ])
  973. ->addConstraint('category_fk', [
  974. 'type' => 'foreign',
  975. 'columns' => ['category_id', 'category_name'],
  976. 'references' => ['categories', ['id', 'name']],
  977. 'update' => 'cascade',
  978. 'delete' => 'cascade'
  979. ]);
  980. $expected = [
  981. 'ALTER TABLE "posts" DROP CONSTRAINT "author_fk";',
  982. 'ALTER TABLE "posts" DROP CONSTRAINT "category_fk";'
  983. ];
  984. $result = $table->dropConstraintSql($connection);
  985. $this->assertCount(2, $result);
  986. $this->assertEquals($expected, $result);
  987. }
  988. /**
  989. * Integration test for converting a Schema\Table into MySQL table creates.
  990. *
  991. * @return void
  992. */
  993. public function testCreateSql()
  994. {
  995. $driver = $this->_getMockedDriver();
  996. $connection = $this->getMockBuilder('Cake\Database\Connection')
  997. ->disableOriginalConstructor()
  998. ->getMock();
  999. $connection->expects($this->any())->method('driver')
  1000. ->will($this->returnValue($driver));
  1001. $table = (new Table('schema_articles'))->addColumn('id', [
  1002. 'type' => 'integer',
  1003. 'null' => false
  1004. ])
  1005. ->addColumn('title', [
  1006. 'type' => 'string',
  1007. 'null' => false,
  1008. 'comment' => 'This is the title',
  1009. ])
  1010. ->addColumn('body', ['type' => 'text'])
  1011. ->addColumn('data', ['type' => 'json'])
  1012. ->addColumn('hash', [
  1013. 'type' => 'string',
  1014. 'fixed' => true,
  1015. 'length' => 40,
  1016. 'collate' => 'C',
  1017. 'null' => false,
  1018. ])
  1019. ->addColumn('created', 'datetime')
  1020. ->addConstraint('primary', [
  1021. 'type' => 'primary',
  1022. 'columns' => ['id'],
  1023. ])
  1024. ->addIndex('title_idx', [
  1025. 'type' => 'index',
  1026. 'columns' => ['title'],
  1027. ]);
  1028. $expected = <<<SQL
  1029. CREATE TABLE "schema_articles" (
  1030. "id" SERIAL,
  1031. "title" VARCHAR NOT NULL,
  1032. "body" TEXT,
  1033. "data" JSONB,
  1034. "hash" CHAR(40) COLLATE "C" NOT NULL,
  1035. "created" TIMESTAMP,
  1036. PRIMARY KEY ("id")
  1037. )
  1038. SQL;
  1039. $result = $table->createSql($connection);
  1040. $this->assertCount(3, $result);
  1041. $this->assertTextEquals($expected, $result[0]);
  1042. $this->assertEquals(
  1043. 'CREATE INDEX "title_idx" ON "schema_articles" ("title")',
  1044. $result[1]
  1045. );
  1046. $this->assertEquals(
  1047. 'COMMENT ON COLUMN "schema_articles"."title" IS \'This is the title\'',
  1048. $result[2]
  1049. );
  1050. }
  1051. /**
  1052. * Tests creating temporary tables
  1053. *
  1054. * @return void
  1055. */
  1056. public function testCreateTemporary()
  1057. {
  1058. $driver = $this->_getMockedDriver();
  1059. $connection = $this->getMockBuilder('Cake\Database\Connection')
  1060. ->disableOriginalConstructor()
  1061. ->getMock();
  1062. $connection->expects($this->any())->method('driver')
  1063. ->will($this->returnValue($driver));
  1064. $table = (new Table('schema_articles'))->addColumn('id', [
  1065. 'type' => 'integer',
  1066. 'null' => false
  1067. ]);
  1068. $table->temporary(true);
  1069. $sql = $table->createSql($connection);
  1070. $this->assertContains('CREATE TEMPORARY TABLE', $sql[0]);
  1071. }
  1072. /**
  1073. * Test primary key generation & auto-increment.
  1074. *
  1075. * @return void
  1076. */
  1077. public function testCreateSqlCompositeIntegerKey()
  1078. {
  1079. $driver = $this->_getMockedDriver();
  1080. $connection = $this->getMockBuilder('Cake\Database\Connection')
  1081. ->disableOriginalConstructor()
  1082. ->getMock();
  1083. $connection->expects($this->any())->method('driver')
  1084. ->will($this->returnValue($driver));
  1085. $table = (new Table('articles_tags'))
  1086. ->addColumn('article_id', [
  1087. 'type' => 'integer',
  1088. 'null' => false
  1089. ])
  1090. ->addColumn('tag_id', [
  1091. 'type' => 'integer',
  1092. 'null' => false,
  1093. ])
  1094. ->addConstraint('primary', [
  1095. 'type' => 'primary',
  1096. 'columns' => ['article_id', 'tag_id']
  1097. ]);
  1098. $expected = <<<SQL
  1099. CREATE TABLE "articles_tags" (
  1100. "article_id" INTEGER NOT NULL,
  1101. "tag_id" INTEGER NOT NULL,
  1102. PRIMARY KEY ("article_id", "tag_id")
  1103. )
  1104. SQL;
  1105. $result = $table->createSql($connection);
  1106. $this->assertCount(1, $result);
  1107. $this->assertTextEquals($expected, $result[0]);
  1108. $table = (new Table('composite_key'))
  1109. ->addColumn('id', [
  1110. 'type' => 'integer',
  1111. 'null' => false,
  1112. 'autoIncrement' => true
  1113. ])
  1114. ->addColumn('account_id', [
  1115. 'type' => 'integer',
  1116. 'null' => false,
  1117. ])
  1118. ->addConstraint('primary', [
  1119. 'type' => 'primary',
  1120. 'columns' => ['id', 'account_id']
  1121. ]);
  1122. $expected = <<<SQL
  1123. CREATE TABLE "composite_key" (
  1124. "id" SERIAL,
  1125. "account_id" INTEGER NOT NULL,
  1126. PRIMARY KEY ("id", "account_id")
  1127. )
  1128. SQL;
  1129. $result = $table->createSql($connection);
  1130. $this->assertCount(1, $result);
  1131. $this->assertTextEquals($expected, $result[0]);
  1132. }
  1133. /**
  1134. * test dropSql
  1135. *
  1136. * @return void
  1137. */
  1138. public function testDropSql()
  1139. {
  1140. $driver = $this->_getMockedDriver();
  1141. $connection = $this->getMockBuilder('Cake\Database\Connection')
  1142. ->disableOriginalConstructor()
  1143. ->getMock();
  1144. $connection->expects($this->any())->method('driver')
  1145. ->will($this->returnValue($driver));
  1146. $table = new Table('schema_articles');
  1147. $result = $table->dropSql($connection);
  1148. $this->assertCount(1, $result);
  1149. $this->assertEquals('DROP TABLE "schema_articles" CASCADE', $result[0]);
  1150. }
  1151. /**
  1152. * Test truncateSql()
  1153. *
  1154. * @return void
  1155. */
  1156. public function testTruncateSql()
  1157. {
  1158. $driver = $this->_getMockedDriver();
  1159. $connection = $this->getMockBuilder('Cake\Database\Connection')
  1160. ->disableOriginalConstructor()
  1161. ->getMock();
  1162. $connection->expects($this->any())->method('driver')
  1163. ->will($this->returnValue($driver));
  1164. $table = new Table('schema_articles');
  1165. $table->addColumn('id', 'integer')
  1166. ->addConstraint('primary', [
  1167. 'type' => 'primary',
  1168. 'columns' => ['id']
  1169. ]);
  1170. $result = $table->truncateSql($connection);
  1171. $this->assertCount(1, $result);
  1172. $this->assertEquals('TRUNCATE "schema_articles" RESTART IDENTITY CASCADE', $result[0]);
  1173. }
  1174. /**
  1175. * Get a schema instance with a mocked driver/pdo instances
  1176. *
  1177. * @return \Cake\Database\Driver
  1178. */
  1179. protected function _getMockedDriver()
  1180. {
  1181. $driver = new Postgres();
  1182. $pdo = PDO::class;
  1183. if (version_compare(PHP_VERSION, '5.6', '<')) {
  1184. $pdo = 'FakePdo';
  1185. }
  1186. $mock = $this->getMockBuilder($pdo)
  1187. ->setMethods(['quote'])
  1188. ->disableOriginalConstructor()
  1189. ->getMock();
  1190. $mock->expects($this->any())
  1191. ->method('quote')
  1192. ->will($this->returnCallback(function ($value) {
  1193. return "'$value'";
  1194. }));
  1195. $driver->connection($mock);
  1196. return $driver;
  1197. }
  1198. }