PostgresSchemaTest.php 31 KB

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