PostgresSchemaTest.php 36 KB

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