PostgresSchemaTest.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272
  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\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' => 'smallinteger', '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' => 'smallinteger',
  337. 'null' => true,
  338. 'default' => 0,
  339. 'length' => 5,
  340. 'precision' => null,
  341. 'unsigned' => null,
  342. 'comment' => 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->getColumn($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->getColumn('id')['autoIncrement'], 'id should be autoincrement');
  415. $this->assertNull($result->getColumn('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->getColumn($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->getConstraint('primary'));
  507. $this->assertEquals($expected['unique_position'], $result->getConstraint('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->getConstraint('primary'));
  555. $this->assertEquals($expected['content_idx'], $result->getConstraint('content_idx'));
  556. $this->assertEquals($expected['author_idx'], $result->getConstraint('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->getIndex('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->getIndex('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. 'id',
  636. ['type' => 'binaryuuid', 'length' => null, 'null' => false],
  637. '"id" UUID NOT NULL'
  638. ],
  639. [
  640. 'role',
  641. ['type' => 'string', 'length' => 10, 'null' => false, 'default' => 'admin'],
  642. '"role" VARCHAR(10) NOT NULL DEFAULT \'admin\''
  643. ],
  644. [
  645. 'title',
  646. ['type' => 'string'],
  647. '"title" VARCHAR'
  648. ],
  649. [
  650. 'title',
  651. ['type' => 'string', 'length' => 255, 'null' => false, 'collate' => 'C'],
  652. '"title" VARCHAR(255) COLLATE "C" NOT NULL'
  653. ],
  654. // Text
  655. [
  656. 'body',
  657. ['type' => 'text', 'null' => false],
  658. '"body" TEXT NOT NULL'
  659. ],
  660. [
  661. 'body',
  662. ['type' => 'text', 'length' => TableSchema::LENGTH_TINY, 'null' => false],
  663. sprintf('"body" VARCHAR(%s) NOT NULL', TableSchema::LENGTH_TINY)
  664. ],
  665. [
  666. 'body',
  667. ['type' => 'text', 'length' => TableSchema::LENGTH_MEDIUM, 'null' => false],
  668. '"body" TEXT NOT NULL'
  669. ],
  670. [
  671. 'body',
  672. ['type' => 'text', 'length' => TableSchema::LENGTH_LONG, 'null' => false],
  673. '"body" TEXT NOT NULL'
  674. ],
  675. [
  676. 'body',
  677. ['type' => 'text', 'null' => false, 'collate' => 'C'],
  678. '"body" TEXT COLLATE "C" NOT NULL'
  679. ],
  680. // Integers
  681. [
  682. 'post_id',
  683. ['type' => 'tinyinteger', 'length' => 11],
  684. '"post_id" SMALLINT'
  685. ],
  686. [
  687. 'post_id',
  688. ['type' => 'smallinteger', 'length' => 11],
  689. '"post_id" SMALLINT'
  690. ],
  691. [
  692. 'post_id',
  693. ['type' => 'integer', 'length' => 11],
  694. '"post_id" INTEGER'
  695. ],
  696. [
  697. 'post_id',
  698. ['type' => 'biginteger', 'length' => 20],
  699. '"post_id" BIGINT'
  700. ],
  701. [
  702. 'post_id',
  703. ['type' => 'integer', 'autoIncrement' => true, 'length' => 11],
  704. '"post_id" SERIAL'
  705. ],
  706. [
  707. 'post_id',
  708. ['type' => 'biginteger', 'autoIncrement' => true, 'length' => 20],
  709. '"post_id" BIGSERIAL'
  710. ],
  711. // Decimal
  712. [
  713. 'value',
  714. ['type' => 'decimal'],
  715. '"value" DECIMAL'
  716. ],
  717. [
  718. 'value',
  719. ['type' => 'decimal', 'length' => 11],
  720. '"value" DECIMAL(11,0)'
  721. ],
  722. [
  723. 'value',
  724. ['type' => 'decimal', 'length' => 12, 'precision' => 5],
  725. '"value" DECIMAL(12,5)'
  726. ],
  727. // Float
  728. [
  729. 'value',
  730. ['type' => 'float'],
  731. '"value" FLOAT'
  732. ],
  733. [
  734. 'value',
  735. ['type' => 'float', 'length' => 11, 'precision' => 3],
  736. '"value" FLOAT(3)'
  737. ],
  738. // Binary
  739. [
  740. 'img',
  741. ['type' => 'binary'],
  742. '"img" BYTEA'
  743. ],
  744. // Boolean
  745. [
  746. 'checked',
  747. ['type' => 'boolean', 'default' => false],
  748. '"checked" BOOLEAN DEFAULT FALSE'
  749. ],
  750. [
  751. 'checked',
  752. ['type' => 'boolean', 'default' => true, 'null' => false],
  753. '"checked" BOOLEAN NOT NULL DEFAULT TRUE'
  754. ],
  755. // Boolean
  756. [
  757. 'checked',
  758. ['type' => 'boolean', 'default' => 0],
  759. '"checked" BOOLEAN DEFAULT FALSE'
  760. ],
  761. [
  762. 'checked',
  763. ['type' => 'boolean', 'default' => 1, 'null' => false],
  764. '"checked" BOOLEAN NOT NULL DEFAULT TRUE'
  765. ],
  766. // Datetime
  767. [
  768. 'created',
  769. ['type' => 'datetime'],
  770. '"created" TIMESTAMP'
  771. ],
  772. [
  773. 'open_date',
  774. ['type' => 'datetime', 'null' => false, 'default' => '2016-12-07 23:04:00'],
  775. '"open_date" TIMESTAMP NOT NULL DEFAULT \'2016-12-07 23:04:00\''
  776. ],
  777. [
  778. 'null_date',
  779. ['type' => 'datetime', 'null' => true],
  780. '"null_date" TIMESTAMP DEFAULT NULL'
  781. ],
  782. [
  783. 'current_timestamp',
  784. ['type' => 'datetime', 'null' => false, 'default' => 'CURRENT_TIMESTAMP'],
  785. '"current_timestamp" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP'
  786. ],
  787. // Date & Time
  788. [
  789. 'start_date',
  790. ['type' => 'date'],
  791. '"start_date" DATE'
  792. ],
  793. [
  794. 'start_time',
  795. ['type' => 'time'],
  796. '"start_time" TIME'
  797. ],
  798. // Timestamp
  799. [
  800. 'created',
  801. ['type' => 'timestamp', 'null' => true],
  802. '"created" TIMESTAMP DEFAULT NULL'
  803. ],
  804. ];
  805. }
  806. /**
  807. * Test generating column definitions
  808. *
  809. * @dataProvider columnSqlProvider
  810. * @return void
  811. */
  812. public function testColumnSql($name, $data, $expected)
  813. {
  814. $driver = $this->_getMockedDriver();
  815. $schema = new PostgresSchema($driver);
  816. $table = (new TableSchema('schema_articles'))->addColumn($name, $data);
  817. $this->assertEquals($expected, $schema->columnSql($table, $name));
  818. }
  819. /**
  820. * Test generating a column that is a primary key.
  821. *
  822. * @return void
  823. */
  824. public function testColumnSqlPrimaryKey()
  825. {
  826. $driver = $this->_getMockedDriver();
  827. $schema = new PostgresSchema($driver);
  828. $table = new TableSchema('schema_articles');
  829. $table->addColumn('id', [
  830. 'type' => 'integer',
  831. 'null' => false
  832. ])
  833. ->addConstraint('primary', [
  834. 'type' => 'primary',
  835. 'columns' => ['id']
  836. ]);
  837. $result = $schema->columnSql($table, 'id');
  838. $this->assertEquals($result, '"id" SERIAL');
  839. }
  840. /**
  841. * Provide data for testing constraintSql
  842. *
  843. * @return array
  844. */
  845. public static function constraintSqlProvider()
  846. {
  847. return [
  848. [
  849. 'primary',
  850. ['type' => 'primary', 'columns' => ['title']],
  851. 'PRIMARY KEY ("title")'
  852. ],
  853. [
  854. 'unique_idx',
  855. ['type' => 'unique', 'columns' => ['title', 'author_id']],
  856. 'CONSTRAINT "unique_idx" UNIQUE ("title", "author_id")'
  857. ],
  858. [
  859. 'author_id_idx',
  860. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id']],
  861. 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
  862. 'REFERENCES "authors" ("id") ON UPDATE RESTRICT ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE'
  863. ],
  864. [
  865. 'author_id_idx',
  866. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'cascade'],
  867. 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
  868. 'REFERENCES "authors" ("id") ON UPDATE CASCADE ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE'
  869. ],
  870. [
  871. 'author_id_idx',
  872. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'restrict'],
  873. 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
  874. 'REFERENCES "authors" ("id") ON UPDATE RESTRICT ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE'
  875. ],
  876. [
  877. 'author_id_idx',
  878. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'setNull'],
  879. 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
  880. 'REFERENCES "authors" ("id") ON UPDATE SET NULL ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE'
  881. ],
  882. [
  883. 'author_id_idx',
  884. ['type' => 'foreign', 'columns' => ['author_id'], 'references' => ['authors', 'id'], 'update' => 'noAction'],
  885. 'CONSTRAINT "author_id_idx" FOREIGN KEY ("author_id") ' .
  886. 'REFERENCES "authors" ("id") ON UPDATE NO ACTION ON DELETE RESTRICT DEFERRABLE INITIALLY IMMEDIATE'
  887. ],
  888. ];
  889. }
  890. /**
  891. * Test the constraintSql method.
  892. *
  893. * @dataProvider constraintSqlProvider
  894. */
  895. public function testConstraintSql($name, $data, $expected)
  896. {
  897. $driver = $this->_getMockedDriver();
  898. $schema = new PostgresSchema($driver);
  899. $table = (new TableSchema('schema_articles'))->addColumn('title', [
  900. 'type' => 'string',
  901. 'length' => 255
  902. ])->addColumn('author_id', [
  903. 'type' => 'integer',
  904. ])->addConstraint($name, $data);
  905. $this->assertTextEquals($expected, $schema->constraintSql($table, $name));
  906. }
  907. /**
  908. * Test the addConstraintSql method.
  909. *
  910. * @return void
  911. */
  912. public function testAddConstraintSql()
  913. {
  914. $driver = $this->_getMockedDriver();
  915. $connection = $this->getMockBuilder('Cake\Database\Connection')
  916. ->disableOriginalConstructor()
  917. ->getMock();
  918. $connection->expects($this->any())->method('getDriver')
  919. ->will($this->returnValue($driver));
  920. $table = (new TableSchema('posts'))
  921. ->addColumn('author_id', [
  922. 'type' => 'integer',
  923. 'null' => false
  924. ])
  925. ->addColumn('category_id', [
  926. 'type' => 'integer',
  927. 'null' => false
  928. ])
  929. ->addColumn('category_name', [
  930. 'type' => 'integer',
  931. 'null' => false
  932. ])
  933. ->addConstraint('author_fk', [
  934. 'type' => 'foreign',
  935. 'columns' => ['author_id'],
  936. 'references' => ['authors', 'id'],
  937. 'update' => 'cascade',
  938. 'delete' => 'cascade'
  939. ])
  940. ->addConstraint('category_fk', [
  941. 'type' => 'foreign',
  942. 'columns' => ['category_id', 'category_name'],
  943. 'references' => ['categories', ['id', 'name']],
  944. 'update' => 'cascade',
  945. 'delete' => 'cascade'
  946. ]);
  947. $expected = [
  948. 'ALTER TABLE "posts" ADD CONSTRAINT "author_fk" FOREIGN KEY ("author_id") REFERENCES "authors" ("id") ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY IMMEDIATE;',
  949. '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;'
  950. ];
  951. $result = $table->addConstraintSql($connection);
  952. $this->assertCount(2, $result);
  953. $this->assertEquals($expected, $result);
  954. }
  955. /**
  956. * Test the dropConstraintSql method.
  957. *
  958. * @return void
  959. */
  960. public function testDropConstraintSql()
  961. {
  962. $driver = $this->_getMockedDriver();
  963. $connection = $this->getMockBuilder('Cake\Database\Connection')
  964. ->disableOriginalConstructor()
  965. ->getMock();
  966. $connection->expects($this->any())->method('getDriver')
  967. ->will($this->returnValue($driver));
  968. $table = (new TableSchema('posts'))
  969. ->addColumn('author_id', [
  970. 'type' => 'integer',
  971. 'null' => false
  972. ])
  973. ->addColumn('category_id', [
  974. 'type' => 'integer',
  975. 'null' => false
  976. ])
  977. ->addColumn('category_name', [
  978. 'type' => 'integer',
  979. 'null' => false
  980. ])
  981. ->addConstraint('author_fk', [
  982. 'type' => 'foreign',
  983. 'columns' => ['author_id'],
  984. 'references' => ['authors', 'id'],
  985. 'update' => 'cascade',
  986. 'delete' => 'cascade'
  987. ])
  988. ->addConstraint('category_fk', [
  989. 'type' => 'foreign',
  990. 'columns' => ['category_id', 'category_name'],
  991. 'references' => ['categories', ['id', 'name']],
  992. 'update' => 'cascade',
  993. 'delete' => 'cascade'
  994. ]);
  995. $expected = [
  996. 'ALTER TABLE "posts" DROP CONSTRAINT "author_fk";',
  997. 'ALTER TABLE "posts" DROP CONSTRAINT "category_fk";'
  998. ];
  999. $result = $table->dropConstraintSql($connection);
  1000. $this->assertCount(2, $result);
  1001. $this->assertEquals($expected, $result);
  1002. }
  1003. /**
  1004. * Integration test for converting a Schema\Table into MySQL table creates.
  1005. *
  1006. * @return void
  1007. */
  1008. public function testCreateSql()
  1009. {
  1010. $driver = $this->_getMockedDriver();
  1011. $connection = $this->getMockBuilder('Cake\Database\Connection')
  1012. ->disableOriginalConstructor()
  1013. ->getMock();
  1014. $connection->expects($this->any())->method('getDriver')
  1015. ->will($this->returnValue($driver));
  1016. $table = (new TableSchema('schema_articles'))->addColumn('id', [
  1017. 'type' => 'integer',
  1018. 'null' => false
  1019. ])
  1020. ->addColumn('title', [
  1021. 'type' => 'string',
  1022. 'null' => false,
  1023. 'comment' => 'This is the title',
  1024. ])
  1025. ->addColumn('body', ['type' => 'text'])
  1026. ->addColumn('data', ['type' => 'json'])
  1027. ->addColumn('hash', [
  1028. 'type' => 'string',
  1029. 'fixed' => true,
  1030. 'length' => 40,
  1031. 'collate' => 'C',
  1032. 'null' => false,
  1033. ])
  1034. ->addColumn('created', 'datetime')
  1035. ->addConstraint('primary', [
  1036. 'type' => 'primary',
  1037. 'columns' => ['id'],
  1038. ])
  1039. ->addIndex('title_idx', [
  1040. 'type' => 'index',
  1041. 'columns' => ['title'],
  1042. ]);
  1043. $expected = <<<SQL
  1044. CREATE TABLE "schema_articles" (
  1045. "id" SERIAL,
  1046. "title" VARCHAR NOT NULL,
  1047. "body" TEXT,
  1048. "data" JSONB,
  1049. "hash" CHAR(40) COLLATE "C" NOT NULL,
  1050. "created" TIMESTAMP,
  1051. PRIMARY KEY ("id")
  1052. )
  1053. SQL;
  1054. $result = $table->createSql($connection);
  1055. $this->assertCount(3, $result);
  1056. $this->assertTextEquals($expected, $result[0]);
  1057. $this->assertEquals(
  1058. 'CREATE INDEX "title_idx" ON "schema_articles" ("title")',
  1059. $result[1]
  1060. );
  1061. $this->assertEquals(
  1062. 'COMMENT ON COLUMN "schema_articles"."title" IS \'This is the title\'',
  1063. $result[2]
  1064. );
  1065. }
  1066. /**
  1067. * Tests creating temporary tables
  1068. *
  1069. * @return void
  1070. */
  1071. public function testCreateTemporary()
  1072. {
  1073. $driver = $this->_getMockedDriver();
  1074. $connection = $this->getMockBuilder('Cake\Database\Connection')
  1075. ->disableOriginalConstructor()
  1076. ->getMock();
  1077. $connection->expects($this->any())->method('getDriver')
  1078. ->will($this->returnValue($driver));
  1079. $table = (new TableSchema('schema_articles'))->addColumn('id', [
  1080. 'type' => 'integer',
  1081. 'null' => false
  1082. ]);
  1083. $table->temporary(true);
  1084. $sql = $table->createSql($connection);
  1085. $this->assertContains('CREATE TEMPORARY TABLE', $sql[0]);
  1086. }
  1087. /**
  1088. * Test primary key generation & auto-increment.
  1089. *
  1090. * @return void
  1091. */
  1092. public function testCreateSqlCompositeIntegerKey()
  1093. {
  1094. $driver = $this->_getMockedDriver();
  1095. $connection = $this->getMockBuilder('Cake\Database\Connection')
  1096. ->disableOriginalConstructor()
  1097. ->getMock();
  1098. $connection->expects($this->any())->method('getDriver')
  1099. ->will($this->returnValue($driver));
  1100. $table = (new TableSchema('articles_tags'))
  1101. ->addColumn('article_id', [
  1102. 'type' => 'integer',
  1103. 'null' => false
  1104. ])
  1105. ->addColumn('tag_id', [
  1106. 'type' => 'integer',
  1107. 'null' => false,
  1108. ])
  1109. ->addConstraint('primary', [
  1110. 'type' => 'primary',
  1111. 'columns' => ['article_id', 'tag_id']
  1112. ]);
  1113. $expected = <<<SQL
  1114. CREATE TABLE "articles_tags" (
  1115. "article_id" INTEGER NOT NULL,
  1116. "tag_id" INTEGER NOT NULL,
  1117. PRIMARY KEY ("article_id", "tag_id")
  1118. )
  1119. SQL;
  1120. $result = $table->createSql($connection);
  1121. $this->assertCount(1, $result);
  1122. $this->assertTextEquals($expected, $result[0]);
  1123. $table = (new TableSchema('composite_key'))
  1124. ->addColumn('id', [
  1125. 'type' => 'integer',
  1126. 'null' => false,
  1127. 'autoIncrement' => true
  1128. ])
  1129. ->addColumn('account_id', [
  1130. 'type' => 'integer',
  1131. 'null' => false,
  1132. ])
  1133. ->addConstraint('primary', [
  1134. 'type' => 'primary',
  1135. 'columns' => ['id', 'account_id']
  1136. ]);
  1137. $expected = <<<SQL
  1138. CREATE TABLE "composite_key" (
  1139. "id" SERIAL,
  1140. "account_id" INTEGER NOT NULL,
  1141. PRIMARY KEY ("id", "account_id")
  1142. )
  1143. SQL;
  1144. $result = $table->createSql($connection);
  1145. $this->assertCount(1, $result);
  1146. $this->assertTextEquals($expected, $result[0]);
  1147. }
  1148. /**
  1149. * test dropSql
  1150. *
  1151. * @return void
  1152. */
  1153. public function testDropSql()
  1154. {
  1155. $driver = $this->_getMockedDriver();
  1156. $connection = $this->getMockBuilder('Cake\Database\Connection')
  1157. ->disableOriginalConstructor()
  1158. ->getMock();
  1159. $connection->expects($this->any())->method('getDriver')
  1160. ->will($this->returnValue($driver));
  1161. $table = new TableSchema('schema_articles');
  1162. $result = $table->dropSql($connection);
  1163. $this->assertCount(1, $result);
  1164. $this->assertEquals('DROP TABLE "schema_articles" CASCADE', $result[0]);
  1165. }
  1166. /**
  1167. * Test truncateSql()
  1168. *
  1169. * @return void
  1170. */
  1171. public function testTruncateSql()
  1172. {
  1173. $driver = $this->_getMockedDriver();
  1174. $connection = $this->getMockBuilder('Cake\Database\Connection')
  1175. ->disableOriginalConstructor()
  1176. ->getMock();
  1177. $connection->expects($this->any())->method('getDriver')
  1178. ->will($this->returnValue($driver));
  1179. $table = new TableSchema('schema_articles');
  1180. $table->addColumn('id', 'integer')
  1181. ->addConstraint('primary', [
  1182. 'type' => 'primary',
  1183. 'columns' => ['id']
  1184. ]);
  1185. $result = $table->truncateSql($connection);
  1186. $this->assertCount(1, $result);
  1187. $this->assertEquals('TRUNCATE "schema_articles" RESTART IDENTITY CASCADE', $result[0]);
  1188. }
  1189. /**
  1190. * Get a schema instance with a mocked driver/pdo instances
  1191. *
  1192. * @return \Cake\Database\Driver
  1193. */
  1194. protected function _getMockedDriver()
  1195. {
  1196. $driver = new Postgres();
  1197. $mock = $this->getMockBuilder(PDO::class)
  1198. ->setMethods(['quote'])
  1199. ->disableOriginalConstructor()
  1200. ->getMock();
  1201. $mock->expects($this->any())
  1202. ->method('quote')
  1203. ->will($this->returnCallback(function ($value) {
  1204. return "'$value'";
  1205. }));
  1206. $driver->connection($mock);
  1207. return $driver;
  1208. }
  1209. }