PostgresSchemaTest.php 42 KB

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