PostgresSchemaTest.php 37 KB

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