PostgresSchemaTest.php 39 KB

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