PostgresSchemaTest.php 35 KB

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