PostgresSchemaTest.php 35 KB

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