PostgresSchemaTest.php 41 KB

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