PostgresSchemaTest.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  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. 'null' => false,
  376. 'default' => null,
  377. 'length' => 10,
  378. 'precision' => null,
  379. 'unsigned' => null,
  380. 'comment' => null,
  381. 'autoIncrement' => true,
  382. ],
  383. 'name' => [
  384. 'type' => 'string',
  385. 'null' => true,
  386. 'default' => 'bob',
  387. 'length' => 50,
  388. 'precision' => null,
  389. 'comment' => null,
  390. 'fixed' => null,
  391. ],
  392. 'bio' => [
  393. 'type' => 'date',
  394. 'null' => true,
  395. 'default' => null,
  396. 'length' => null,
  397. 'precision' => null,
  398. 'comment' => null,
  399. ],
  400. 'position' => [
  401. 'type' => 'integer',
  402. 'null' => true,
  403. 'default' => '1',
  404. 'length' => 10,
  405. 'precision' => null,
  406. 'comment' => null,
  407. 'unsigned' => null,
  408. 'autoIncrement' => null,
  409. ],
  410. 'created' => [
  411. 'type' => 'timestamp',
  412. 'null' => true,
  413. 'default' => null,
  414. 'length' => null,
  415. 'precision' => null,
  416. 'comment' => null,
  417. ],
  418. ];
  419. $this->assertEquals(['id'], $result->primaryKey());
  420. foreach ($expected as $field => $definition) {
  421. $this->assertEquals($definition, $result->column($field), "Mismatch in $field column");
  422. }
  423. }
  424. /**
  425. * Test describing a table with containing keywords
  426. *
  427. * @return void
  428. */
  429. public function testDescribeTableConstraintsWithKeywords()
  430. {
  431. $connection = ConnectionManager::get('test');
  432. $this->_createTables($connection);
  433. $schema = new SchemaCollection($connection);
  434. $result = $schema->describe('schema_authors');
  435. $this->assertInstanceOf('Cake\Database\Schema\Table', $result);
  436. $expected = [
  437. 'primary' => [
  438. 'type' => 'primary',
  439. 'columns' => ['id'],
  440. 'length' => []
  441. ],
  442. 'unique_position' => [
  443. 'type' => 'unique',
  444. 'columns' => ['position'],
  445. 'length' => []
  446. ]
  447. ];
  448. $this->assertCount(2, $result->constraints());
  449. $this->assertEquals($expected['primary'], $result->constraint('primary'));
  450. $this->assertEquals($expected['unique_position'], $result->constraint('unique_position'));
  451. }
  452. /**
  453. * Test describing a table with indexes
  454. *
  455. * @return void
  456. */
  457. public function testDescribeTableIndexes()
  458. {
  459. $connection = ConnectionManager::get('test');
  460. $this->_createTables($connection);
  461. $schema = new SchemaCollection($connection);
  462. $result = $schema->describe('schema_articles');
  463. $this->assertInstanceOf('Cake\Database\Schema\Table', $result);
  464. $expected = [
  465. 'primary' => [
  466. 'type' => 'primary',
  467. 'columns' => ['id'],
  468. 'length' => []
  469. ],
  470. 'content_idx' => [
  471. 'type' => 'unique',
  472. 'columns' => ['title', 'body'],
  473. 'length' => []
  474. ]
  475. ];
  476. $this->assertCount(3, $result->constraints());
  477. $expected = [
  478. 'primary' => [
  479. 'type' => 'primary',
  480. 'columns' => ['id'],
  481. 'length' => []
  482. ],
  483. 'content_idx' => [
  484. 'type' => 'unique',
  485. 'columns' => ['title', 'body'],
  486. 'length' => []
  487. ],
  488. 'author_idx' => [
  489. 'type' => 'foreign',
  490. 'columns' => ['author_id'],
  491. 'references' => ['schema_authors', 'id'],
  492. 'length' => [],
  493. 'update' => 'cascade',
  494. 'delete' => 'restrict',
  495. ]
  496. ];
  497. $this->assertEquals($expected['primary'], $result->constraint('primary'));
  498. $this->assertEquals($expected['content_idx'], $result->constraint('content_idx'));
  499. $this->assertEquals($expected['author_idx'], $result->constraint('author_idx'));
  500. $this->assertCount(1, $result->indexes());
  501. $expected = [
  502. 'type' => 'index',
  503. 'columns' => ['author_id'],
  504. 'length' => []
  505. ];
  506. $this->assertEquals($expected, $result->index('author_idx'));
  507. }
  508. /**
  509. * Column provider for creating column sql
  510. *
  511. * @return array
  512. */
  513. public static function columnSqlProvider()
  514. {
  515. return [
  516. // strings
  517. [
  518. 'title',
  519. ['type' => 'string', 'length' => 25, 'null' => false],
  520. '"title" VARCHAR(25) NOT NULL'
  521. ],
  522. [
  523. 'title',
  524. ['type' => 'string', 'length' => 25, 'null' => true, 'default' => 'ignored'],
  525. '"title" VARCHAR(25) DEFAULT NULL'
  526. ],
  527. [
  528. 'id',
  529. ['type' => 'string', 'length' => 32, 'fixed' => true, 'null' => false],
  530. '"id" CHAR(32) NOT NULL'
  531. ],
  532. [
  533. 'id',
  534. ['type' => 'uuid', 'length' => 36, 'null' => false],
  535. '"id" UUID NOT NULL'
  536. ],
  537. [
  538. 'role',
  539. ['type' => 'string', 'length' => 10, 'null' => false, 'default' => 'admin'],
  540. '"role" VARCHAR(10) NOT NULL DEFAULT "admin"'
  541. ],
  542. [
  543. 'title',
  544. ['type' => 'string'],
  545. '"title" VARCHAR'
  546. ],
  547. // Text
  548. [
  549. 'body',
  550. ['type' => 'text', 'null' => false],
  551. '"body" TEXT NOT NULL'
  552. ],
  553. // Integers
  554. [
  555. 'post_id',
  556. ['type' => 'integer', 'length' => 11],
  557. '"post_id" INTEGER'
  558. ],
  559. [
  560. 'post_id',
  561. ['type' => 'biginteger', 'length' => 20],
  562. '"post_id" BIGINT'
  563. ],
  564. [
  565. 'post_id',
  566. ['type' => 'integer', 'autoIncrement' => true, 'length' => 11],
  567. '"post_id" SERIAL'
  568. ],
  569. [
  570. 'post_id',
  571. ['type' => 'biginteger', 'autoIncrement' => true, 'length' => 20],
  572. '"post_id" BIGSERIAL'
  573. ],
  574. // Decimal
  575. [
  576. 'value',
  577. ['type' => 'decimal'],
  578. '"value" DECIMAL'
  579. ],
  580. [
  581. 'value',
  582. ['type' => 'decimal', 'length' => 11],
  583. '"value" DECIMAL(11,0)'
  584. ],
  585. [
  586. 'value',
  587. ['type' => 'decimal', 'length' => 12, 'precision' => 5],
  588. '"value" DECIMAL(12,5)'
  589. ],
  590. // Float
  591. [
  592. 'value',
  593. ['type' => 'float'],
  594. '"value" FLOAT'
  595. ],
  596. [
  597. 'value',
  598. ['type' => 'float', 'length' => 11, 'precision' => 3],
  599. '"value" FLOAT(3)'
  600. ],
  601. // Binary
  602. [
  603. 'img',
  604. ['type' => 'binary'],
  605. '"img" BYTEA'
  606. ],
  607. // Boolean
  608. [
  609. 'checked',
  610. ['type' => 'boolean', 'default' => false],
  611. '"checked" BOOLEAN DEFAULT FALSE'
  612. ],
  613. [
  614. 'checked',
  615. ['type' => 'boolean', 'default' => true, 'null' => false],
  616. '"checked" BOOLEAN NOT NULL DEFAULT TRUE'
  617. ],
  618. // Boolean
  619. [
  620. 'checked',
  621. ['type' => 'boolean', 'default' => 0],
  622. '"checked" BOOLEAN DEFAULT FALSE'
  623. ],
  624. [
  625. 'checked',
  626. ['type' => 'boolean', 'default' => 1, 'null' => false],
  627. '"checked" BOOLEAN NOT NULL DEFAULT TRUE'
  628. ],
  629. // datetimes
  630. [
  631. 'created',
  632. ['type' => 'datetime'],
  633. '"created" TIMESTAMP'
  634. ],
  635. // Date & Time
  636. [
  637. 'start_date',
  638. ['type' => 'date'],
  639. '"start_date" DATE'
  640. ],
  641. [
  642. 'start_time',
  643. ['type' => 'time'],
  644. '"start_time" TIME'
  645. ],
  646. // timestamps
  647. [
  648. 'created',
  649. ['type' => 'timestamp', 'null' => true],
  650. '"created" TIMESTAMP DEFAULT NULL'
  651. ],
  652. ];
  653. }
  654. /**
  655. * Test generating column definitions
  656. *
  657. * @dataProvider columnSqlProvider
  658. * @return void
  659. */
  660. public function testColumnSql($name, $data, $expected)
  661. {
  662. $driver = $this->_getMockedDriver();
  663. $schema = new PostgresSchema($driver);
  664. $table = (new Table('schema_articles'))->addColumn($name, $data);
  665. $this->assertEquals($expected, $schema->columnSql($table, $name));
  666. }
  667. /**
  668. * Test generating a column that is a primary key.
  669. *
  670. * @return void
  671. */
  672. public function testColumnSqlPrimaryKey()
  673. {
  674. $driver = $this->_getMockedDriver();
  675. $schema = new PostgresSchema($driver);
  676. $table = new Table('schema_articles');
  677. $table->addColumn('id', [
  678. 'type' => 'integer',
  679. 'null' => false
  680. ])
  681. ->addConstraint('primary', [
  682. 'type' => 'primary',
  683. 'columns' => ['id']
  684. ]);
  685. $result = $schema->columnSql($table, 'id');
  686. $this->assertEquals($result, '"id" SERIAL');
  687. }
  688. /**
  689. * Provide data for testing constraintSql
  690. *
  691. * @return array
  692. */
  693. public static function constraintSqlProvider()
  694. {
  695. return [
  696. [
  697. 'primary',
  698. ['type' => 'primary', 'columns' => ['title']],
  699. 'PRIMARY KEY ("title")'
  700. ],
  701. [
  702. 'unique_idx',
  703. ['type' => 'unique', 'columns' => ['title', 'author_id']],
  704. 'CONSTRAINT "unique_idx" UNIQUE ("title", "author_id")'
  705. ],
  706. [
  707. 'author_id_idx',
  708. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id']],
  709. 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
  710. 'REFERENCES "authors" ("id") ON UPDATE RESTRICT ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE'
  711. ],
  712. [
  713. 'author_id_idx',
  714. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'cascade'],
  715. 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
  716. 'REFERENCES "authors" ("id") ON UPDATE CASCADE ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE'
  717. ],
  718. [
  719. 'author_id_idx',
  720. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'restrict'],
  721. 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
  722. 'REFERENCES "authors" ("id") ON UPDATE RESTRICT ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE'
  723. ],
  724. [
  725. 'author_id_idx',
  726. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'setNull'],
  727. 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
  728. 'REFERENCES "authors" ("id") ON UPDATE SET NULL ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE'
  729. ],
  730. [
  731. 'author_id_idx',
  732. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'noAction'],
  733. 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
  734. 'REFERENCES "authors" ("id") ON UPDATE NO ACTION ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE'
  735. ],
  736. ];
  737. }
  738. /**
  739. * Test the constraintSql method.
  740. *
  741. * @dataProvider constraintSqlProvider
  742. */
  743. public function testConstraintSql($name, $data, $expected)
  744. {
  745. $driver = $this->_getMockedDriver();
  746. $schema = new PostgresSchema($driver);
  747. $table = (new Table('schema_articles'))->addColumn('title', [
  748. 'type' => 'string',
  749. 'length' => 255
  750. ])->addColumn('author_id', [
  751. 'type' => 'integer',
  752. ])->addConstraint($name, $data);
  753. $this->assertTextEquals($expected, $schema->constraintSql($table, $name));
  754. }
  755. /**
  756. * Integration test for converting a Schema\Table into MySQL table creates.
  757. *
  758. * @return void
  759. */
  760. public function testCreateSql()
  761. {
  762. $driver = $this->_getMockedDriver();
  763. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  764. $connection->expects($this->any())->method('driver')
  765. ->will($this->returnValue($driver));
  766. $table = (new Table('schema_articles'))->addColumn('id', [
  767. 'type' => 'integer',
  768. 'null' => false
  769. ])
  770. ->addColumn('title', [
  771. 'type' => 'string',
  772. 'null' => false,
  773. 'comment' => 'This is the title',
  774. ])
  775. ->addColumn('body', ['type' => 'text'])
  776. ->addColumn('created', 'datetime')
  777. ->addConstraint('primary', [
  778. 'type' => 'primary',
  779. 'columns' => ['id'],
  780. ])
  781. ->addIndex('title_idx', [
  782. 'type' => 'index',
  783. 'columns' => ['title'],
  784. ]);
  785. $expected = <<<SQL
  786. CREATE TABLE "schema_articles" (
  787. "id" SERIAL,
  788. "title" VARCHAR NOT NULL,
  789. "body" TEXT,
  790. "created" TIMESTAMP,
  791. PRIMARY KEY ("id")
  792. )
  793. SQL;
  794. $result = $table->createSql($connection);
  795. $this->assertCount(3, $result);
  796. $this->assertTextEquals($expected, $result[0]);
  797. $this->assertEquals(
  798. 'CREATE INDEX "title_idx" ON "schema_articles" ("title")',
  799. $result[1]
  800. );
  801. $this->assertEquals(
  802. 'COMMENT ON COLUMN "schema_articles"."title" IS "This is the title"',
  803. $result[2]
  804. );
  805. }
  806. /**
  807. * Tests creating temporary tables
  808. *
  809. * @return void
  810. */
  811. public function testCreateTemporary()
  812. {
  813. $driver = $this->_getMockedDriver();
  814. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  815. $connection->expects($this->any())->method('driver')
  816. ->will($this->returnValue($driver));
  817. $table = (new Table('schema_articles'))->addColumn('id', [
  818. 'type' => 'integer',
  819. 'null' => false
  820. ]);
  821. $table->temporary(true);
  822. $sql = $table->createSql($connection);
  823. $this->assertContains('CREATE TEMPORARY TABLE', $sql[0]);
  824. }
  825. /**
  826. * Test primary key generation & auto-increment.
  827. *
  828. * @return void
  829. */
  830. public function testCreateSqlCompositeIntegerKey()
  831. {
  832. $driver = $this->_getMockedDriver();
  833. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  834. $connection->expects($this->any())->method('driver')
  835. ->will($this->returnValue($driver));
  836. $table = (new Table('articles_tags'))
  837. ->addColumn('article_id', [
  838. 'type' => 'integer',
  839. 'null' => false
  840. ])
  841. ->addColumn('tag_id', [
  842. 'type' => 'integer',
  843. 'null' => false,
  844. ])
  845. ->addConstraint('primary', [
  846. 'type' => 'primary',
  847. 'columns' => ['article_id', 'tag_id']
  848. ]);
  849. $expected = <<<SQL
  850. CREATE TABLE "articles_tags" (
  851. "article_id" INTEGER NOT NULL,
  852. "tag_id" INTEGER NOT NULL,
  853. PRIMARY KEY ("article_id", "tag_id")
  854. )
  855. SQL;
  856. $result = $table->createSql($connection);
  857. $this->assertCount(1, $result);
  858. $this->assertTextEquals($expected, $result[0]);
  859. $table = (new Table('composite_key'))
  860. ->addColumn('id', [
  861. 'type' => 'integer',
  862. 'null' => false,
  863. 'autoIncrement' => true
  864. ])
  865. ->addColumn('account_id', [
  866. 'type' => 'integer',
  867. 'null' => false,
  868. ])
  869. ->addConstraint('primary', [
  870. 'type' => 'primary',
  871. 'columns' => ['id', 'account_id']
  872. ]);
  873. $expected = <<<SQL
  874. CREATE TABLE "composite_key" (
  875. "id" SERIAL,
  876. "account_id" INTEGER NOT NULL,
  877. PRIMARY KEY ("id", "account_id")
  878. )
  879. SQL;
  880. $result = $table->createSql($connection);
  881. $this->assertCount(1, $result);
  882. $this->assertTextEquals($expected, $result[0]);
  883. }
  884. /**
  885. * test dropSql
  886. *
  887. * @return void
  888. */
  889. public function testDropSql()
  890. {
  891. $driver = $this->_getMockedDriver();
  892. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  893. $connection->expects($this->any())->method('driver')
  894. ->will($this->returnValue($driver));
  895. $table = new Table('schema_articles');
  896. $result = $table->dropSql($connection);
  897. $this->assertCount(1, $result);
  898. $this->assertEquals('DROP TABLE "schema_articles" CASCADE', $result[0]);
  899. }
  900. /**
  901. * Test truncateSql()
  902. *
  903. * @return void
  904. */
  905. public function testTruncateSql()
  906. {
  907. $driver = $this->_getMockedDriver();
  908. $connection = $this->getMock('Cake\Database\Connection', [], [], '', false);
  909. $connection->expects($this->any())->method('driver')
  910. ->will($this->returnValue($driver));
  911. $table = new Table('schema_articles');
  912. $table->addColumn('id', 'integer')
  913. ->addConstraint('primary', [
  914. 'type' => 'primary',
  915. 'columns' => ['id']
  916. ]);
  917. $result = $table->truncateSql($connection);
  918. $this->assertCount(1, $result);
  919. $this->assertEquals('TRUNCATE "schema_articles" RESTART IDENTITY CASCADE', $result[0]);
  920. }
  921. /**
  922. * Get a schema instance with a mocked driver/pdo instances
  923. *
  924. * @return Driver
  925. */
  926. protected function _getMockedDriver()
  927. {
  928. $driver = new \Cake\Database\Driver\Postgres();
  929. $mock = $this->getMock('FakePdo', ['quote', 'quoteIdentifier']);
  930. $mock->expects($this->any())
  931. ->method('quote')
  932. ->will($this->returnCallback(function ($value) {
  933. return '"' . $value . '"';
  934. }));
  935. $mock->expects($this->any())
  936. ->method('quoteIdentifier')
  937. ->will($this->returnCallback(function ($value) {
  938. return '"' . $value . '"';
  939. }));
  940. $driver->connection($mock);
  941. return $driver;
  942. }
  943. }