PostgresSchemaTest.php 36 KB

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