PostgresSchemaTest.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://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. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license https://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\TableSchema;
  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' => 'smallinteger', '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(TableSchema::class)
  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' => 'smallinteger',
  336. 'null' => true,
  337. 'default' => 0,
  338. 'length' => 5,
  339. 'precision' => null,
  340. 'unsigned' => null,
  341. 'comment' => null,
  342. ],
  343. 'readingtime' => [
  344. 'type' => 'time',
  345. 'null' => true,
  346. 'default' => null,
  347. 'length' => null,
  348. 'precision' => null,
  349. 'comment' => null,
  350. ],
  351. 'data' => [
  352. 'type' => 'json',
  353. 'null' => true,
  354. 'default' => null,
  355. 'length' => null,
  356. 'precision' => null,
  357. 'comment' => null,
  358. ],
  359. 'average_note' => [
  360. 'type' => 'decimal',
  361. 'null' => true,
  362. 'default' => null,
  363. 'length' => 4,
  364. 'precision' => 2,
  365. 'unsigned' => null,
  366. 'comment' => null,
  367. ],
  368. 'average_income' => [
  369. 'type' => 'decimal',
  370. 'null' => true,
  371. 'default' => null,
  372. 'length' => 10,
  373. 'precision' => 2,
  374. 'unsigned' => null,
  375. 'comment' => null,
  376. ],
  377. 'created' => [
  378. 'type' => 'timestamp',
  379. 'null' => true,
  380. 'default' => null,
  381. 'length' => null,
  382. 'precision' => null,
  383. 'comment' => null,
  384. ],
  385. ];
  386. $this->assertEquals(['id'], $result->primaryKey());
  387. foreach ($expected as $field => $definition) {
  388. $this->assertEquals($definition, $result->column($field));
  389. }
  390. }
  391. /**
  392. * Test describing a table with postgres and composite keys
  393. *
  394. * @return void
  395. */
  396. public function testDescribeTableCompositeKey()
  397. {
  398. $this->_needsConnection();
  399. $connection = ConnectionManager::get('test');
  400. $sql = <<<SQL
  401. CREATE TABLE schema_composite (
  402. "id" SERIAL,
  403. "site_id" INTEGER NOT NULL,
  404. "name" VARCHAR(255),
  405. PRIMARY KEY("id", "site_id")
  406. );
  407. SQL;
  408. $connection->execute($sql);
  409. $schema = new SchemaCollection($connection);
  410. $result = $schema->describe('schema_composite');
  411. $connection->execute('DROP TABLE schema_composite');
  412. $this->assertEquals(['id', 'site_id'], $result->primaryKey());
  413. $this->assertTrue($result->column('id')['autoIncrement'], 'id should be autoincrement');
  414. $this->assertNull($result->column('site_id')['autoIncrement'], 'site_id should not be autoincrement');
  415. }
  416. /**
  417. * Test describing a table containing defaults with Postgres
  418. *
  419. * @return void
  420. */
  421. public function testDescribeTableWithDefaults()
  422. {
  423. $connection = ConnectionManager::get('test');
  424. $this->_createTables($connection);
  425. $schema = new SchemaCollection($connection);
  426. $result = $schema->describe('schema_authors');
  427. $expected = [
  428. 'id' => [
  429. 'type' => 'integer',
  430. 'null' => false,
  431. 'default' => null,
  432. 'length' => 10,
  433. 'precision' => null,
  434. 'unsigned' => null,
  435. 'comment' => null,
  436. 'autoIncrement' => true,
  437. ],
  438. 'name' => [
  439. 'type' => 'string',
  440. 'null' => true,
  441. 'default' => 'bob',
  442. 'length' => 50,
  443. 'precision' => null,
  444. 'comment' => null,
  445. 'fixed' => null,
  446. 'collate' => null,
  447. ],
  448. 'bio' => [
  449. 'type' => 'date',
  450. 'null' => true,
  451. 'default' => null,
  452. 'length' => null,
  453. 'precision' => null,
  454. 'comment' => null,
  455. ],
  456. 'position' => [
  457. 'type' => 'integer',
  458. 'null' => true,
  459. 'default' => '1',
  460. 'length' => 10,
  461. 'precision' => null,
  462. 'comment' => null,
  463. 'unsigned' => null,
  464. 'autoIncrement' => null,
  465. ],
  466. 'created' => [
  467. 'type' => 'timestamp',
  468. 'null' => true,
  469. 'default' => null,
  470. 'length' => null,
  471. 'precision' => null,
  472. 'comment' => null,
  473. ],
  474. ];
  475. $this->assertEquals(['id'], $result->primaryKey());
  476. foreach ($expected as $field => $definition) {
  477. $this->assertEquals($definition, $result->column($field), "Mismatch in $field column");
  478. }
  479. }
  480. /**
  481. * Test describing a table with containing keywords
  482. *
  483. * @return void
  484. */
  485. public function testDescribeTableConstraintsWithKeywords()
  486. {
  487. $connection = ConnectionManager::get('test');
  488. $this->_createTables($connection);
  489. $schema = new SchemaCollection($connection);
  490. $result = $schema->describe('schema_authors');
  491. $this->assertInstanceOf('Cake\Database\Schema\Table', $result);
  492. $expected = [
  493. 'primary' => [
  494. 'type' => 'primary',
  495. 'columns' => ['id'],
  496. 'length' => []
  497. ],
  498. 'unique_position' => [
  499. 'type' => 'unique',
  500. 'columns' => ['position'],
  501. 'length' => []
  502. ]
  503. ];
  504. $this->assertCount(2, $result->constraints());
  505. $this->assertEquals($expected['primary'], $result->constraint('primary'));
  506. $this->assertEquals($expected['unique_position'], $result->constraint('unique_position'));
  507. }
  508. /**
  509. * Test describing a table with indexes
  510. *
  511. * @return void
  512. */
  513. public function testDescribeTableIndexes()
  514. {
  515. $connection = ConnectionManager::get('test');
  516. $this->_createTables($connection);
  517. $schema = new SchemaCollection($connection);
  518. $result = $schema->describe('schema_articles');
  519. $this->assertInstanceOf('Cake\Database\Schema\Table', $result);
  520. $expected = [
  521. 'primary' => [
  522. 'type' => 'primary',
  523. 'columns' => ['id'],
  524. 'length' => []
  525. ],
  526. 'content_idx' => [
  527. 'type' => 'unique',
  528. 'columns' => ['title', 'body'],
  529. 'length' => []
  530. ]
  531. ];
  532. $this->assertCount(3, $result->constraints());
  533. $expected = [
  534. 'primary' => [
  535. 'type' => 'primary',
  536. 'columns' => ['id'],
  537. 'length' => []
  538. ],
  539. 'content_idx' => [
  540. 'type' => 'unique',
  541. 'columns' => ['title', 'body'],
  542. 'length' => []
  543. ],
  544. 'author_idx' => [
  545. 'type' => 'foreign',
  546. 'columns' => ['author_id'],
  547. 'references' => ['schema_authors', 'id'],
  548. 'length' => [],
  549. 'update' => 'cascade',
  550. 'delete' => 'restrict',
  551. ]
  552. ];
  553. $this->assertEquals($expected['primary'], $result->constraint('primary'));
  554. $this->assertEquals($expected['content_idx'], $result->constraint('content_idx'));
  555. $this->assertEquals($expected['author_idx'], $result->constraint('author_idx'));
  556. $this->assertCount(1, $result->indexes());
  557. $expected = [
  558. 'type' => 'index',
  559. 'columns' => ['author_id'],
  560. 'length' => []
  561. ];
  562. $this->assertEquals($expected, $result->index('author_idx'));
  563. }
  564. /**
  565. * Test describing a table with indexes with nulls first
  566. *
  567. * @return void
  568. */
  569. public function testDescribeTableIndexesNullsFirst()
  570. {
  571. $this->_needsConnection();
  572. $connection = ConnectionManager::get('test');
  573. $connection->execute('DROP TABLE IF EXISTS schema_index');
  574. $table = <<<SQL
  575. CREATE TABLE schema_index (
  576. id serial NOT NULL,
  577. user_id integer NOT NULL,
  578. group_id integer NOT NULL,
  579. grade double precision
  580. )
  581. WITH (
  582. OIDS=FALSE
  583. )
  584. SQL;
  585. $connection->execute($table);
  586. $index = <<<SQL
  587. CREATE INDEX schema_index_nulls
  588. ON schema_index
  589. USING btree
  590. (group_id, grade DESC NULLS FIRST);
  591. SQL;
  592. $connection->execute($index);
  593. $schema = new SchemaCollection($connection);
  594. $result = $schema->describe('schema_index');
  595. $this->assertCount(1, $result->indexes());
  596. $expected = [
  597. 'type' => 'index',
  598. 'columns' => ['group_id', 'grade'],
  599. 'length' => []
  600. ];
  601. $this->assertEquals($expected, $result->index('schema_index_nulls'));
  602. $connection->execute('DROP TABLE schema_index');
  603. }
  604. /**
  605. * Column provider for creating column sql
  606. *
  607. * @return array
  608. */
  609. public static function columnSqlProvider()
  610. {
  611. return [
  612. // strings
  613. [
  614. 'title',
  615. ['type' => 'string', 'length' => 25, 'null' => false],
  616. '"title" VARCHAR(25) NOT NULL'
  617. ],
  618. [
  619. 'title',
  620. ['type' => 'string', 'length' => 25, 'null' => true, 'default' => 'ignored'],
  621. '"title" VARCHAR(25) DEFAULT \'ignored\'',
  622. ],
  623. [
  624. 'id',
  625. ['type' => 'string', 'length' => 32, 'fixed' => true, 'null' => false],
  626. '"id" CHAR(32) NOT NULL'
  627. ],
  628. [
  629. 'id',
  630. ['type' => 'uuid', 'length' => 36, 'null' => false],
  631. '"id" UUID NOT NULL'
  632. ],
  633. [
  634. 'role',
  635. ['type' => 'string', 'length' => 10, 'null' => false, 'default' => 'admin'],
  636. '"role" VARCHAR(10) NOT NULL DEFAULT \'admin\''
  637. ],
  638. [
  639. 'title',
  640. ['type' => 'string'],
  641. '"title" VARCHAR'
  642. ],
  643. [
  644. 'title',
  645. ['type' => 'string', 'length' => 255, 'null' => false, 'collate' => 'C'],
  646. '"title" VARCHAR(255) COLLATE "C" NOT NULL'
  647. ],
  648. // Text
  649. [
  650. 'body',
  651. ['type' => 'text', 'null' => false],
  652. '"body" TEXT NOT NULL'
  653. ],
  654. [
  655. 'body',
  656. ['type' => 'text', 'length' => TableSchema::LENGTH_TINY, 'null' => false],
  657. sprintf('"body" VARCHAR(%s) NOT NULL', TableSchema::LENGTH_TINY)
  658. ],
  659. [
  660. 'body',
  661. ['type' => 'text', 'length' => TableSchema::LENGTH_MEDIUM, 'null' => false],
  662. '"body" TEXT NOT NULL'
  663. ],
  664. [
  665. 'body',
  666. ['type' => 'text', 'length' => TableSchema::LENGTH_LONG, 'null' => false],
  667. '"body" TEXT NOT NULL'
  668. ],
  669. [
  670. 'body',
  671. ['type' => 'text', 'null' => false, 'collate' => 'C'],
  672. '"body" TEXT COLLATE "C" NOT NULL'
  673. ],
  674. // Integers
  675. [
  676. 'post_id',
  677. ['type' => 'tinyinteger', 'length' => 11],
  678. '"post_id" SMALLINT'
  679. ],
  680. [
  681. 'post_id',
  682. ['type' => 'smallinteger', 'length' => 11],
  683. '"post_id" SMALLINT'
  684. ],
  685. [
  686. 'post_id',
  687. ['type' => 'integer', 'length' => 11],
  688. '"post_id" INTEGER'
  689. ],
  690. [
  691. 'post_id',
  692. ['type' => 'biginteger', 'length' => 20],
  693. '"post_id" BIGINT'
  694. ],
  695. [
  696. 'post_id',
  697. ['type' => 'integer', 'autoIncrement' => true, 'length' => 11],
  698. '"post_id" SERIAL'
  699. ],
  700. [
  701. 'post_id',
  702. ['type' => 'biginteger', 'autoIncrement' => true, 'length' => 20],
  703. '"post_id" BIGSERIAL'
  704. ],
  705. // Decimal
  706. [
  707. 'value',
  708. ['type' => 'decimal'],
  709. '"value" DECIMAL'
  710. ],
  711. [
  712. 'value',
  713. ['type' => 'decimal', 'length' => 11],
  714. '"value" DECIMAL(11,0)'
  715. ],
  716. [
  717. 'value',
  718. ['type' => 'decimal', 'length' => 12, 'precision' => 5],
  719. '"value" DECIMAL(12,5)'
  720. ],
  721. // Float
  722. [
  723. 'value',
  724. ['type' => 'float'],
  725. '"value" FLOAT'
  726. ],
  727. [
  728. 'value',
  729. ['type' => 'float', 'length' => 11, 'precision' => 3],
  730. '"value" FLOAT(3)'
  731. ],
  732. // Binary
  733. [
  734. 'img',
  735. ['type' => 'binary'],
  736. '"img" BYTEA'
  737. ],
  738. // Boolean
  739. [
  740. 'checked',
  741. ['type' => 'boolean', 'default' => false],
  742. '"checked" BOOLEAN DEFAULT FALSE'
  743. ],
  744. [
  745. 'checked',
  746. ['type' => 'boolean', 'default' => true, 'null' => false],
  747. '"checked" BOOLEAN NOT NULL DEFAULT TRUE'
  748. ],
  749. // Boolean
  750. [
  751. 'checked',
  752. ['type' => 'boolean', 'default' => 0],
  753. '"checked" BOOLEAN DEFAULT FALSE'
  754. ],
  755. [
  756. 'checked',
  757. ['type' => 'boolean', 'default' => 1, 'null' => false],
  758. '"checked" BOOLEAN NOT NULL DEFAULT TRUE'
  759. ],
  760. // Datetime
  761. [
  762. 'created',
  763. ['type' => 'datetime'],
  764. '"created" TIMESTAMP'
  765. ],
  766. [
  767. 'open_date',
  768. ['type' => 'datetime', 'null' => false, 'default' => '2016-12-07 23:04:00'],
  769. '"open_date" TIMESTAMP NOT NULL DEFAULT \'2016-12-07 23:04:00\''
  770. ],
  771. [
  772. 'null_date',
  773. ['type' => 'datetime', 'null' => true],
  774. '"null_date" TIMESTAMP DEFAULT NULL'
  775. ],
  776. [
  777. 'current_timestamp',
  778. ['type' => 'datetime', 'null' => false, 'default' => 'CURRENT_TIMESTAMP'],
  779. '"current_timestamp" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP'
  780. ],
  781. // Date & Time
  782. [
  783. 'start_date',
  784. ['type' => 'date'],
  785. '"start_date" DATE'
  786. ],
  787. [
  788. 'start_time',
  789. ['type' => 'time'],
  790. '"start_time" TIME'
  791. ],
  792. // Timestamp
  793. [
  794. 'created',
  795. ['type' => 'timestamp', 'null' => true],
  796. '"created" TIMESTAMP DEFAULT NULL'
  797. ],
  798. ];
  799. }
  800. /**
  801. * Test generating column definitions
  802. *
  803. * @dataProvider columnSqlProvider
  804. * @return void
  805. */
  806. public function testColumnSql($name, $data, $expected)
  807. {
  808. $driver = $this->_getMockedDriver();
  809. $schema = new PostgresSchema($driver);
  810. $table = (new TableSchema('schema_articles'))->addColumn($name, $data);
  811. $this->assertEquals($expected, $schema->columnSql($table, $name));
  812. }
  813. /**
  814. * Test generating a column that is a primary key.
  815. *
  816. * @return void
  817. */
  818. public function testColumnSqlPrimaryKey()
  819. {
  820. $driver = $this->_getMockedDriver();
  821. $schema = new PostgresSchema($driver);
  822. $table = new TableSchema('schema_articles');
  823. $table->addColumn('id', [
  824. 'type' => 'integer',
  825. 'null' => false
  826. ])
  827. ->addConstraint('primary', [
  828. 'type' => 'primary',
  829. 'columns' => ['id']
  830. ]);
  831. $result = $schema->columnSql($table, 'id');
  832. $this->assertEquals($result, '"id" SERIAL');
  833. }
  834. /**
  835. * Provide data for testing constraintSql
  836. *
  837. * @return array
  838. */
  839. public static function constraintSqlProvider()
  840. {
  841. return [
  842. [
  843. 'primary',
  844. ['type' => 'primary', 'columns' => ['title']],
  845. 'PRIMARY KEY ("title")'
  846. ],
  847. [
  848. 'unique_idx',
  849. ['type' => 'unique', 'columns' => ['title', 'author_id']],
  850. 'CONSTRAINT "unique_idx" UNIQUE ("title", "author_id")'
  851. ],
  852. [
  853. 'author_id_idx',
  854. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id']],
  855. 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
  856. 'REFERENCES "authors" ("id") ON UPDATE RESTRICT ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE'
  857. ],
  858. [
  859. 'author_id_idx',
  860. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'cascade'],
  861. 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
  862. 'REFERENCES "authors" ("id") ON UPDATE CASCADE ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE'
  863. ],
  864. [
  865. 'author_id_idx',
  866. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'restrict'],
  867. 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
  868. 'REFERENCES "authors" ("id") ON UPDATE RESTRICT ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE'
  869. ],
  870. [
  871. 'author_id_idx',
  872. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'setNull'],
  873. 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
  874. 'REFERENCES "authors" ("id") ON UPDATE SET NULL ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE'
  875. ],
  876. [
  877. 'author_id_idx',
  878. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'noAction'],
  879. 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
  880. 'REFERENCES "authors" ("id") ON UPDATE NO ACTION ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE'
  881. ],
  882. ];
  883. }
  884. /**
  885. * Test the constraintSql method.
  886. *
  887. * @dataProvider constraintSqlProvider
  888. */
  889. public function testConstraintSql($name, $data, $expected)
  890. {
  891. $driver = $this->_getMockedDriver();
  892. $schema = new PostgresSchema($driver);
  893. $table = (new TableSchema('schema_articles'))->addColumn('title', [
  894. 'type' => 'string',
  895. 'length' => 255
  896. ])->addColumn('author_id', [
  897. 'type' => 'integer',
  898. ])->addConstraint($name, $data);
  899. $this->assertTextEquals($expected, $schema->constraintSql($table, $name));
  900. }
  901. /**
  902. * Test the addConstraintSql method.
  903. *
  904. * @return void
  905. */
  906. public function testAddConstraintSql()
  907. {
  908. $driver = $this->_getMockedDriver();
  909. $connection = $this->getMockBuilder('Cake\Database\Connection')
  910. ->disableOriginalConstructor()
  911. ->getMock();
  912. $connection->expects($this->any())->method('getDriver')
  913. ->will($this->returnValue($driver));
  914. $table = (new TableSchema('posts'))
  915. ->addColumn('author_id', [
  916. 'type' => 'integer',
  917. 'null' => false
  918. ])
  919. ->addColumn('category_id', [
  920. 'type' => 'integer',
  921. 'null' => false
  922. ])
  923. ->addColumn('category_name', [
  924. 'type' => 'integer',
  925. 'null' => false
  926. ])
  927. ->addConstraint('author_fk', [
  928. 'type' => 'foreign',
  929. 'columns' => ['author_id'],
  930. 'references' => ['authors', 'id'],
  931. 'update' => 'cascade',
  932. 'delete' => 'cascade'
  933. ])
  934. ->addConstraint('category_fk', [
  935. 'type' => 'foreign',
  936. 'columns' => ['category_id', 'category_name'],
  937. 'references' => ['categories', ['id', 'name']],
  938. 'update' => 'cascade',
  939. 'delete' => 'cascade'
  940. ]);
  941. $expected = [
  942. 'ALTER TABLE "posts" ADD CONSTRAINT "author_fk" FOREIGN KEY ("author_id") REFERENCES "authors" ("id") ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY IMMEDIATE;',
  943. '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;'
  944. ];
  945. $result = $table->addConstraintSql($connection);
  946. $this->assertCount(2, $result);
  947. $this->assertEquals($expected, $result);
  948. }
  949. /**
  950. * Test the dropConstraintSql method.
  951. *
  952. * @return void
  953. */
  954. public function testDropConstraintSql()
  955. {
  956. $driver = $this->_getMockedDriver();
  957. $connection = $this->getMockBuilder('Cake\Database\Connection')
  958. ->disableOriginalConstructor()
  959. ->getMock();
  960. $connection->expects($this->any())->method('getDriver')
  961. ->will($this->returnValue($driver));
  962. $table = (new TableSchema('posts'))
  963. ->addColumn('author_id', [
  964. 'type' => 'integer',
  965. 'null' => false
  966. ])
  967. ->addColumn('category_id', [
  968. 'type' => 'integer',
  969. 'null' => false
  970. ])
  971. ->addColumn('category_name', [
  972. 'type' => 'integer',
  973. 'null' => false
  974. ])
  975. ->addConstraint('author_fk', [
  976. 'type' => 'foreign',
  977. 'columns' => ['author_id'],
  978. 'references' => ['authors', 'id'],
  979. 'update' => 'cascade',
  980. 'delete' => 'cascade'
  981. ])
  982. ->addConstraint('category_fk', [
  983. 'type' => 'foreign',
  984. 'columns' => ['category_id', 'category_name'],
  985. 'references' => ['categories', ['id', 'name']],
  986. 'update' => 'cascade',
  987. 'delete' => 'cascade'
  988. ]);
  989. $expected = [
  990. 'ALTER TABLE "posts" DROP CONSTRAINT "author_fk";',
  991. 'ALTER TABLE "posts" DROP CONSTRAINT "category_fk";'
  992. ];
  993. $result = $table->dropConstraintSql($connection);
  994. $this->assertCount(2, $result);
  995. $this->assertEquals($expected, $result);
  996. }
  997. /**
  998. * Integration test for converting a Schema\Table into MySQL table creates.
  999. *
  1000. * @return void
  1001. */
  1002. public function testCreateSql()
  1003. {
  1004. $driver = $this->_getMockedDriver();
  1005. $connection = $this->getMockBuilder('Cake\Database\Connection')
  1006. ->disableOriginalConstructor()
  1007. ->getMock();
  1008. $connection->expects($this->any())->method('getDriver')
  1009. ->will($this->returnValue($driver));
  1010. $table = (new TableSchema('schema_articles'))->addColumn('id', [
  1011. 'type' => 'integer',
  1012. 'null' => false
  1013. ])
  1014. ->addColumn('title', [
  1015. 'type' => 'string',
  1016. 'null' => false,
  1017. 'comment' => 'This is the title',
  1018. ])
  1019. ->addColumn('body', ['type' => 'text'])
  1020. ->addColumn('data', ['type' => 'json'])
  1021. ->addColumn('hash', [
  1022. 'type' => 'string',
  1023. 'fixed' => true,
  1024. 'length' => 40,
  1025. 'collate' => 'C',
  1026. 'null' => false,
  1027. ])
  1028. ->addColumn('created', 'datetime')
  1029. ->addConstraint('primary', [
  1030. 'type' => 'primary',
  1031. 'columns' => ['id'],
  1032. ])
  1033. ->addIndex('title_idx', [
  1034. 'type' => 'index',
  1035. 'columns' => ['title'],
  1036. ]);
  1037. $expected = <<<SQL
  1038. CREATE TABLE "schema_articles" (
  1039. "id" SERIAL,
  1040. "title" VARCHAR NOT NULL,
  1041. "body" TEXT,
  1042. "data" JSONB,
  1043. "hash" CHAR(40) COLLATE "C" NOT NULL,
  1044. "created" TIMESTAMP,
  1045. PRIMARY KEY ("id")
  1046. )
  1047. SQL;
  1048. $result = $table->createSql($connection);
  1049. $this->assertCount(3, $result);
  1050. $this->assertTextEquals($expected, $result[0]);
  1051. $this->assertEquals(
  1052. 'CREATE INDEX "title_idx" ON "schema_articles" ("title")',
  1053. $result[1]
  1054. );
  1055. $this->assertEquals(
  1056. 'COMMENT ON COLUMN "schema_articles"."title" IS \'This is the title\'',
  1057. $result[2]
  1058. );
  1059. }
  1060. /**
  1061. * Tests creating temporary tables
  1062. *
  1063. * @return void
  1064. */
  1065. public function testCreateTemporary()
  1066. {
  1067. $driver = $this->_getMockedDriver();
  1068. $connection = $this->getMockBuilder('Cake\Database\Connection')
  1069. ->disableOriginalConstructor()
  1070. ->getMock();
  1071. $connection->expects($this->any())->method('getDriver')
  1072. ->will($this->returnValue($driver));
  1073. $table = (new TableSchema('schema_articles'))->addColumn('id', [
  1074. 'type' => 'integer',
  1075. 'null' => false
  1076. ]);
  1077. $table->temporary(true);
  1078. $sql = $table->createSql($connection);
  1079. $this->assertContains('CREATE TEMPORARY TABLE', $sql[0]);
  1080. }
  1081. /**
  1082. * Test primary key generation & auto-increment.
  1083. *
  1084. * @return void
  1085. */
  1086. public function testCreateSqlCompositeIntegerKey()
  1087. {
  1088. $driver = $this->_getMockedDriver();
  1089. $connection = $this->getMockBuilder('Cake\Database\Connection')
  1090. ->disableOriginalConstructor()
  1091. ->getMock();
  1092. $connection->expects($this->any())->method('getDriver')
  1093. ->will($this->returnValue($driver));
  1094. $table = (new TableSchema('articles_tags'))
  1095. ->addColumn('article_id', [
  1096. 'type' => 'integer',
  1097. 'null' => false
  1098. ])
  1099. ->addColumn('tag_id', [
  1100. 'type' => 'integer',
  1101. 'null' => false,
  1102. ])
  1103. ->addConstraint('primary', [
  1104. 'type' => 'primary',
  1105. 'columns' => ['article_id', 'tag_id']
  1106. ]);
  1107. $expected = <<<SQL
  1108. CREATE TABLE "articles_tags" (
  1109. "article_id" INTEGER NOT NULL,
  1110. "tag_id" INTEGER NOT NULL,
  1111. PRIMARY KEY ("article_id", "tag_id")
  1112. )
  1113. SQL;
  1114. $result = $table->createSql($connection);
  1115. $this->assertCount(1, $result);
  1116. $this->assertTextEquals($expected, $result[0]);
  1117. $table = (new TableSchema('composite_key'))
  1118. ->addColumn('id', [
  1119. 'type' => 'integer',
  1120. 'null' => false,
  1121. 'autoIncrement' => true
  1122. ])
  1123. ->addColumn('account_id', [
  1124. 'type' => 'integer',
  1125. 'null' => false,
  1126. ])
  1127. ->addConstraint('primary', [
  1128. 'type' => 'primary',
  1129. 'columns' => ['id', 'account_id']
  1130. ]);
  1131. $expected = <<<SQL
  1132. CREATE TABLE "composite_key" (
  1133. "id" SERIAL,
  1134. "account_id" INTEGER NOT NULL,
  1135. PRIMARY KEY ("id", "account_id")
  1136. )
  1137. SQL;
  1138. $result = $table->createSql($connection);
  1139. $this->assertCount(1, $result);
  1140. $this->assertTextEquals($expected, $result[0]);
  1141. }
  1142. /**
  1143. * test dropSql
  1144. *
  1145. * @return void
  1146. */
  1147. public function testDropSql()
  1148. {
  1149. $driver = $this->_getMockedDriver();
  1150. $connection = $this->getMockBuilder('Cake\Database\Connection')
  1151. ->disableOriginalConstructor()
  1152. ->getMock();
  1153. $connection->expects($this->any())->method('getDriver')
  1154. ->will($this->returnValue($driver));
  1155. $table = new TableSchema('schema_articles');
  1156. $result = $table->dropSql($connection);
  1157. $this->assertCount(1, $result);
  1158. $this->assertEquals('DROP TABLE "schema_articles" CASCADE', $result[0]);
  1159. }
  1160. /**
  1161. * Test truncateSql()
  1162. *
  1163. * @return void
  1164. */
  1165. public function testTruncateSql()
  1166. {
  1167. $driver = $this->_getMockedDriver();
  1168. $connection = $this->getMockBuilder('Cake\Database\Connection')
  1169. ->disableOriginalConstructor()
  1170. ->getMock();
  1171. $connection->expects($this->any())->method('getDriver')
  1172. ->will($this->returnValue($driver));
  1173. $table = new TableSchema('schema_articles');
  1174. $table->addColumn('id', 'integer')
  1175. ->addConstraint('primary', [
  1176. 'type' => 'primary',
  1177. 'columns' => ['id']
  1178. ]);
  1179. $result = $table->truncateSql($connection);
  1180. $this->assertCount(1, $result);
  1181. $this->assertEquals('TRUNCATE "schema_articles" RESTART IDENTITY CASCADE', $result[0]);
  1182. }
  1183. /**
  1184. * Get a schema instance with a mocked driver/pdo instances
  1185. *
  1186. * @return \Cake\Database\Driver
  1187. */
  1188. protected function _getMockedDriver()
  1189. {
  1190. $driver = new Postgres();
  1191. $mock = $this->getMockBuilder(PDO::class)
  1192. ->setMethods(['quote'])
  1193. ->disableOriginalConstructor()
  1194. ->getMock();
  1195. $mock->expects($this->any())
  1196. ->method('quote')
  1197. ->will($this->returnCallback(function ($value) {
  1198. return "'$value'";
  1199. }));
  1200. $driver->connection($mock);
  1201. return $driver;
  1202. }
  1203. }