PostgresSchemaTest.php 31 KB

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