PostgresSchemaTest.php 22 KB

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