PostgresSchemaTest.php 34 KB

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