PostgresSchemaTest.php 40 KB

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