PostgresSchemaTest.php 38 KB

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