PostgresSchemaTest.php 39 KB

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