PostgresSchemaTest.php 30 KB

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