PostgresSchemaTest.php 29 KB

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