PostgresAdapter.php 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163
  1. <?php
  2. /**
  3. * Phinx
  4. *
  5. * (The MIT license)
  6. * Copyright (c) 2015 Rob Morgan
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated * documentation files (the "Software"), to
  10. * deal in the Software without restriction, including without limitation the
  11. * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  12. * sell copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  23. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  24. * IN THE SOFTWARE.
  25. *
  26. * @package Phinx
  27. * @subpackage Phinx\Db\Adapter
  28. */
  29. namespace BBDDL\Db\Adapter;
  30. use BBDDL\Db\Table;
  31. use BBDDL\Db\Table\Column;
  32. use BBDDL\Db\Table\Index;
  33. use BBDDL\Db\Table\ForeignKey;
  34. class PostgresAdapter extends PdoAdapter implements AdapterInterface
  35. {
  36. const INT_SMALL = 65535;
  37. protected $options = Array();
  38. /**
  39. * Columns with comments
  40. *
  41. * @var array
  42. */
  43. protected $columnsWithComments = array();
  44. private function getOptions(){
  45. return $this->options;
  46. }
  47. /**
  48. * {@inheritdoc}
  49. */
  50. public function connect()
  51. {
  52. }
  53. /**
  54. * {@inheritdoc}
  55. */
  56. public function disconnect()
  57. {
  58. $this->connection = null;
  59. }
  60. /**
  61. * {@inheritdoc}
  62. */
  63. public function hasTransactions()
  64. {
  65. return true;
  66. }
  67. /**
  68. * {@inheritdoc}
  69. */
  70. public function beginTransaction()
  71. {
  72. $this->execute('BEGIN');
  73. }
  74. /**
  75. * {@inheritdoc}
  76. */
  77. public function commitTransaction()
  78. {
  79. $this->execute('COMMIT');
  80. }
  81. /**
  82. * {@inheritdoc}
  83. */
  84. public function rollbackTransaction()
  85. {
  86. $this->execute('ROLLBACK');
  87. }
  88. /**
  89. * Quotes a schema name for use in a query.
  90. *
  91. * @param string $schemaName Schema Name
  92. * @return string
  93. */
  94. public function quoteSchemaName($schemaName)
  95. {
  96. return $this->quoteColumnName($schemaName);
  97. }
  98. /**
  99. * {@inheritdoc}
  100. */
  101. public function quoteTableName($tableName)
  102. {
  103. return $this->quoteSchemaName($this->getSchemaName()) . '.' . $this->quoteColumnName($tableName);
  104. }
  105. /**
  106. * {@inheritdoc}
  107. */
  108. public function quoteColumnName($columnName)
  109. {
  110. return '"'. $columnName . '"';
  111. }
  112. /**
  113. * {@inheritdoc}
  114. */
  115. public function hasTable($tableName)
  116. {
  117. $result = $this->getConnection()->query(
  118. sprintf(
  119. 'SELECT *
  120. FROM information_schema.tables
  121. WHERE table_schema = %s
  122. AND lower(table_name) = lower(%s)',
  123. $this->getConnection()->quote($this->getSchemaName()),
  124. $this->getConnection()->quote($tableName)
  125. )
  126. );
  127. return $result->rowCount() === 1;
  128. }
  129. /**
  130. * {@inheritdoc}
  131. */
  132. public function createTable(Table $table)
  133. {
  134. $this->startCommandTimer();
  135. $options = $table->getOptions();
  136. // Add the default primary key
  137. $columns = $table->getPendingColumns();
  138. if (!isset($options['id']) || (isset($options['id']) && $options['id'] === true)) {
  139. $column = new Column();
  140. $column->setName('id')
  141. ->setType('integer')
  142. ->setIdentity(true);
  143. array_unshift($columns, $column);
  144. $options['primary_key'] = 'id';
  145. } elseif (isset($options['id']) && is_string($options['id'])) {
  146. // Handle id => "field_name" to support AUTO_INCREMENT
  147. $column = new Column();
  148. $column->setName($options['id'])
  149. ->setType('integer')
  150. ->setIdentity(true);
  151. array_unshift($columns, $column);
  152. $options['primary_key'] = $options['id'];
  153. }
  154. // TODO - process table options like collation etc
  155. $sql = 'CREATE TABLE ';
  156. $sql .= $this->quoteTableName($table->getName()) . ' (';
  157. $this->columnsWithComments = array();
  158. foreach ($columns as $column) {
  159. $sql .= $this->quoteColumnName($column->getName()) . ' ' . $this->getColumnSqlDefinition($column) . ', ';
  160. // set column comments, if needed
  161. if ($column->getComment()) {
  162. $this->columnsWithComments[] = $column;
  163. }
  164. }
  165. // set the primary key(s)
  166. if (isset($options['primary_key'])) {
  167. $sql = rtrim($sql);
  168. $sql .= sprintf(' CONSTRAINT %s_pkey PRIMARY KEY (', $table->getName());
  169. if (is_string($options['primary_key'])) { // handle primary_key => 'id'
  170. $sql .= $this->quoteColumnName($options['primary_key']);
  171. } elseif (is_array($options['primary_key'])) { // handle primary_key => array('tag_id', 'resource_id')
  172. // PHP 5.4 will allow access of $this, so we can call quoteColumnName() directly in the anonymous function,
  173. // but for now just hard-code the adapter quotes
  174. $sql .= implode(
  175. ',',
  176. array_map(
  177. function ($v) {
  178. return '"' . $v . '"';
  179. },
  180. $options['primary_key']
  181. )
  182. );
  183. }
  184. $sql .= ')';
  185. } else {
  186. $sql = substr(rtrim($sql), 0, -1); // no primary keys
  187. }
  188. // set the foreign keys
  189. $foreignKeys = $table->getForeignKeys();
  190. if (!empty($foreignKeys)) {
  191. foreach ($foreignKeys as $foreignKey) {
  192. $sql .= ', ' . $this->getForeignKeySqlDefinition($foreignKey, $table->getName());
  193. }
  194. }
  195. $sql .= ');';
  196. // process column comments
  197. if (!empty($this->columnsWithComments)) {
  198. foreach ($this->columnsWithComments as $column) {
  199. $sql .= $this->getColumnCommentSqlDefinition($column, $table->getName());
  200. }
  201. }
  202. // set the indexes
  203. $indexes = $table->getIndexes();
  204. if (!empty($indexes)) {
  205. foreach ($indexes as $index) {
  206. $sql .= $this->getIndexSqlDefinition($index, $table->getName());
  207. }
  208. }
  209. // execute the sql
  210. $this->writeCommand('createTable', array($table->getName()));
  211. $this->execute($sql);
  212. // process table comments
  213. if (isset($options['comment'])) {
  214. $sql = sprintf(
  215. 'COMMENT ON TABLE %s IS %s',
  216. $this->quoteTableName($table->getName()),
  217. $this->getConnection()->quote($options['comment'])
  218. );
  219. $this->execute($sql);
  220. }
  221. $this->endCommandTimer();
  222. }
  223. /**
  224. * {@inheritdoc}
  225. */
  226. public function renameTable($tableName, $newTableName)
  227. {
  228. $this->startCommandTimer();
  229. $this->writeCommand('renameTable', array($tableName, $newTableName));
  230. $sql = sprintf(
  231. 'ALTER TABLE %s RENAME TO %s',
  232. $this->quoteTableName($tableName),
  233. $this->quoteColumnName($newTableName)
  234. );
  235. $this->execute($sql);
  236. $this->endCommandTimer();
  237. }
  238. /**
  239. * {@inheritdoc}
  240. */
  241. public function dropTable($tableName)
  242. {
  243. $this->startCommandTimer();
  244. $this->writeCommand('dropTable', array($tableName));
  245. $this->execute(sprintf('DROP TABLE %s', $this->quoteTableName($tableName)));
  246. $this->endCommandTimer();
  247. }
  248. /**
  249. * {@inheritdoc}
  250. */
  251. public function getColumns($tableName)
  252. {
  253. $columns = array();
  254. $sql = sprintf(
  255. "SELECT column_name, data_type, is_identity, is_nullable,
  256. column_default, character_maximum_length, numeric_precision, numeric_scale
  257. FROM information_schema.columns
  258. WHERE table_name ='%s'",
  259. $tableName
  260. );
  261. $columnsInfo = $this->fetchAll($sql);
  262. foreach ($columnsInfo as $columnInfo) {
  263. $column = new Column();
  264. $column->setName($columnInfo['column_name'])
  265. ->setType($this->getPhinxType($columnInfo['data_type']))
  266. ->setNull($columnInfo['is_nullable'] === 'YES')
  267. ->setDefault($columnInfo['column_default'])
  268. ->setIdentity($columnInfo['is_identity'] === 'YES')
  269. ->setPrecision($columnInfo['numeric_precision'])
  270. ->setScale($columnInfo['numeric_scale']);
  271. if (preg_match('/\bwith time zone$/', $columnInfo['data_type'])) {
  272. $column->setTimezone(true);
  273. }
  274. if (isset($columnInfo['character_maximum_length'])) {
  275. $column->setLimit($columnInfo['character_maximum_length']);
  276. }
  277. $columns[] = $column;
  278. }
  279. return $columns;
  280. }
  281. /**
  282. * {@inheritdoc}
  283. */
  284. public function hasColumn($tableName, $columnName, $options = array())
  285. {
  286. $sql = sprintf("SELECT count(*)
  287. FROM information_schema.columns
  288. WHERE table_schema = '%s' AND table_name = '%s' AND column_name = '%s'",
  289. $this->getSchemaName(),
  290. $tableName,
  291. $columnName
  292. );
  293. $result = $this->fetchRow($sql);
  294. return $result['count'] > 0;
  295. }
  296. /**
  297. * {@inheritdoc}
  298. */
  299. public function addColumn(Table $table, Column $column)
  300. {
  301. $this->startCommandTimer();
  302. $this->writeCommand('addColumn', array($table->getName(), $column->getName(), $column->getType()));
  303. $sql = sprintf(
  304. 'ALTER TABLE %s ADD %s %s',
  305. $this->quoteTableName($table->getName()),
  306. $this->quoteColumnName($column->getName()),
  307. $this->getColumnSqlDefinition($column)
  308. );
  309. $this->execute($sql);
  310. $this->endCommandTimer();
  311. }
  312. /**
  313. * {@inheritdoc}
  314. */
  315. public function renameColumn($tableName, $columnName, $newColumnName)
  316. {
  317. $this->startCommandTimer();
  318. $sql = sprintf(
  319. "SELECT CASE WHEN COUNT(*) > 0 THEN 1 ELSE 0 END AS column_exists
  320. FROM information_schema.columns
  321. WHERE table_name ='%s' AND column_name = '%s'",
  322. $tableName,
  323. $columnName
  324. );
  325. $result = $this->fetchRow($sql);
  326. if (!(bool) $result['column_exists']) {
  327. throw new \InvalidArgumentException("The specified column does not exist: $columnName");
  328. }
  329. $this->writeCommand('renameColumn', array($tableName, $columnName, $newColumnName));
  330. $this->execute(
  331. sprintf(
  332. 'ALTER TABLE %s RENAME COLUMN %s TO %s',
  333. $this->quoteTableName($tableName),
  334. $this->quoteColumnName($columnName),
  335. $newColumnName
  336. )
  337. );
  338. $this->endCommandTimer();
  339. }
  340. /**
  341. * {@inheritdoc}
  342. */
  343. public function changeColumn($tableName, $columnName, Column $newColumn)
  344. {
  345. // TODO - is it possible to merge these 3 queries into less?
  346. $this->startCommandTimer();
  347. $this->writeCommand('changeColumn', array($tableName, $columnName, $newColumn->getType()));
  348. // change data type
  349. $sql = sprintf(
  350. 'ALTER TABLE %s ALTER COLUMN %s TYPE %s',
  351. $this->quoteTableName($tableName),
  352. $this->quoteColumnName($columnName),
  353. $this->getColumnSqlDefinition($newColumn)
  354. );
  355. //NULL and DEFAULT cannot be set while changing column type
  356. $sql = preg_replace('/ NOT NULL/', '', $sql);
  357. $sql = preg_replace('/ NULL/', '', $sql);
  358. //If it is set, DEFAULT is the last definition
  359. $sql = preg_replace('/DEFAULT .*/', '', $sql);
  360. $this->execute($sql);
  361. // process null
  362. $sql = sprintf(
  363. 'ALTER TABLE %s ALTER COLUMN %s',
  364. $this->quoteTableName($tableName),
  365. $this->quoteColumnName($columnName)
  366. );
  367. if ($newColumn->isNull()) {
  368. $sql .= ' DROP NOT NULL';
  369. } else {
  370. $sql .= ' SET NOT NULL';
  371. }
  372. $this->execute($sql);
  373. if (!is_null($newColumn->getDefault())) {
  374. //change default
  375. $this->execute(
  376. sprintf(
  377. 'ALTER TABLE %s ALTER COLUMN %s SET %s',
  378. $this->quoteTableName($tableName),
  379. $this->quoteColumnName($columnName),
  380. $this->getDefaultValueDefinition($newColumn->getDefault())
  381. )
  382. );
  383. }
  384. else {
  385. //drop default
  386. $this->execute(
  387. sprintf(
  388. 'ALTER TABLE %s ALTER COLUMN %s DROP DEFAULT',
  389. $this->quoteTableName($tableName),
  390. $this->quoteColumnName($columnName)
  391. )
  392. );
  393. }
  394. // rename column
  395. if ($columnName !== $newColumn->getName()) {
  396. $this->execute(
  397. sprintf(
  398. 'ALTER TABLE %s RENAME COLUMN %s TO %s',
  399. $this->quoteTableName($tableName),
  400. $this->quoteColumnName($columnName),
  401. $this->quoteColumnName($newColumn->getName())
  402. )
  403. );
  404. }
  405. // change column comment if needed
  406. if ($newColumn->getComment()) {
  407. $sql = $this->getColumnCommentSqlDefinition($newColumn, $tableName);
  408. $this->execute($sql);
  409. }
  410. $this->endCommandTimer();
  411. }
  412. /**
  413. * {@inheritdoc}
  414. */
  415. public function dropColumn($tableName, $columnName)
  416. {
  417. $this->startCommandTimer();
  418. $this->writeCommand('dropColumn', array($tableName, $columnName));
  419. $this->execute(
  420. sprintf(
  421. 'ALTER TABLE %s DROP COLUMN %s',
  422. $this->quoteTableName($tableName),
  423. $this->quoteColumnName($columnName)
  424. )
  425. );
  426. $this->endCommandTimer();
  427. }
  428. /**
  429. * Get an array of indexes from a particular table.
  430. *
  431. * @param string $tableName Table Name
  432. * @return array
  433. */
  434. protected function getIndexes($tableName)
  435. {
  436. $indexes = array();
  437. $sql = "SELECT
  438. i.relname AS index_name,
  439. a.attname AS column_name
  440. FROM
  441. pg_class t,
  442. pg_class i,
  443. pg_index ix,
  444. pg_attribute a
  445. WHERE
  446. t.oid = ix.indrelid
  447. AND i.oid = ix.indexrelid
  448. AND a.attrelid = t.oid
  449. AND a.attnum = ANY(ix.indkey)
  450. AND t.relkind = 'r'
  451. AND t.relname = '$tableName'
  452. ORDER BY
  453. t.relname,
  454. i.relname;";
  455. $rows = $this->fetchAll($sql);
  456. foreach ($rows as $row) {
  457. if (!isset($indexes[$row['index_name']])) {
  458. $indexes[$row['index_name']] = array('columns' => array());
  459. }
  460. $indexes[$row['index_name']]['columns'][] = strtolower($row['column_name']);
  461. }
  462. return $indexes;
  463. }
  464. /**
  465. * {@inheritdoc}
  466. */
  467. public function hasIndex($tableName, $columns)
  468. {
  469. if (is_string($columns)) {
  470. $columns = array($columns);
  471. }
  472. $columns = array_map('strtolower', $columns);
  473. $indexes = $this->getIndexes($tableName);
  474. foreach ($indexes as $index) {
  475. if (array_diff($index['columns'], $columns) === array_diff($columns, $index['columns'])) {
  476. return true;
  477. }
  478. }
  479. return false;
  480. }
  481. /**
  482. * {@inheritdoc}
  483. */
  484. public function hasIndexByName($tableName, $indexName)
  485. {
  486. $indexes = $this->getIndexes($tableName);
  487. foreach ($indexes as $name => $index) {
  488. if ($name === $indexName) {
  489. return true;
  490. }
  491. }
  492. return false;
  493. }
  494. /**
  495. * {@inheritdoc}
  496. */
  497. public function addIndex(Table $table, Index $index)
  498. {
  499. $this->startCommandTimer();
  500. $this->writeCommand('addIndex', array($table->getName(), $index->getColumns()));
  501. $sql = $this->getIndexSqlDefinition($index, $table->getName());
  502. $this->execute($sql);
  503. $this->endCommandTimer();
  504. }
  505. /**
  506. * {@inheritdoc}
  507. */
  508. public function dropIndex($tableName, $columns)
  509. {
  510. $this->startCommandTimer();
  511. if (is_string($columns)) {
  512. $columns = array($columns); // str to array
  513. }
  514. $this->writeCommand('dropIndex', array($tableName, $columns));
  515. $indexes = $this->getIndexes($tableName);
  516. $columns = array_map('strtolower', $columns);
  517. foreach ($indexes as $indexName => $index) {
  518. $a = array_diff($columns, $index['columns']);
  519. if (empty($a)) {
  520. $this->execute(
  521. sprintf(
  522. 'DROP INDEX IF EXISTS %s',
  523. $this->quoteColumnName($indexName)
  524. )
  525. );
  526. $this->endCommandTimer();
  527. return;
  528. }
  529. }
  530. }
  531. /**
  532. * {@inheritdoc}
  533. */
  534. public function dropIndexByName($tableName, $indexName)
  535. {
  536. $this->startCommandTimer();
  537. $this->writeCommand('dropIndexByName', array($tableName, $indexName));
  538. $sql = sprintf(
  539. 'DROP INDEX IF EXISTS %s',
  540. $indexName
  541. );
  542. $this->execute($sql);
  543. $this->endCommandTimer();
  544. }
  545. /**
  546. * {@inheritdoc}
  547. */
  548. public function hasForeignKey($tableName, $columns, $constraint = null)
  549. {
  550. if (is_string($columns)) {
  551. $columns = array($columns); // str to array
  552. }
  553. $foreignKeys = $this->getForeignKeys($tableName);
  554. if ($constraint) {
  555. if (isset($foreignKeys[$constraint])) {
  556. return !empty($foreignKeys[$constraint]);
  557. }
  558. return false;
  559. } else {
  560. foreach ($foreignKeys as $key) {
  561. $a = array_diff($columns, $key['columns']);
  562. if (empty($a)) {
  563. return true;
  564. }
  565. }
  566. return false;
  567. }
  568. }
  569. /**
  570. * Get an array of foreign keys from a particular table.
  571. *
  572. * @param string $tableName Table Name
  573. * @return array
  574. */
  575. protected function getForeignKeys($tableName)
  576. {
  577. $foreignKeys = array();
  578. $rows = $this->fetchAll(sprintf(
  579. "SELECT
  580. tc.constraint_name,
  581. tc.table_name, kcu.column_name,
  582. ccu.table_name AS referenced_table_name,
  583. ccu.column_name AS referenced_column_name
  584. FROM
  585. information_schema.table_constraints AS tc
  586. JOIN information_schema.key_column_usage AS kcu ON tc.constraint_name = kcu.constraint_name
  587. JOIN information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name
  588. WHERE constraint_type = 'FOREIGN KEY' AND tc.table_name = '%s'
  589. ORDER BY kcu.position_in_unique_constraint",
  590. $tableName
  591. ));
  592. foreach ($rows as $row) {
  593. $foreignKeys[$row['constraint_name']]['table'] = $row['table_name'];
  594. $foreignKeys[$row['constraint_name']]['columns'][] = $row['column_name'];
  595. $foreignKeys[$row['constraint_name']]['referenced_table'] = $row['referenced_table_name'];
  596. $foreignKeys[$row['constraint_name']]['referenced_columns'][] = $row['referenced_column_name'];
  597. }
  598. return $foreignKeys;
  599. }
  600. /**
  601. * {@inheritdoc}
  602. */
  603. public function addForeignKey(Table $table, ForeignKey $foreignKey)
  604. {
  605. $this->startCommandTimer();
  606. $this->writeCommand('addForeignKey', array($table->getName(), $foreignKey->getColumns()));
  607. $sql = sprintf(
  608. 'ALTER TABLE %s ADD %s',
  609. $this->quoteTableName($table->getName()),
  610. $this->getForeignKeySqlDefinition($foreignKey, $table->getName())
  611. );
  612. $this->execute($sql);
  613. $this->endCommandTimer();
  614. }
  615. /**
  616. * {@inheritdoc}
  617. */
  618. public function dropForeignKey($tableName, $columns, $constraint = null)
  619. {
  620. $this->startCommandTimer();
  621. if (is_string($columns)) {
  622. $columns = array($columns); // str to array
  623. }
  624. $this->writeCommand('dropForeignKey', array($tableName, $columns));
  625. if ($constraint) {
  626. $this->execute(
  627. sprintf(
  628. 'ALTER TABLE %s DROP CONSTRAINT %s',
  629. $this->quoteTableName($tableName),
  630. $constraint
  631. )
  632. );
  633. } else {
  634. foreach ($columns as $column) {
  635. $rows = $this->fetchAll(sprintf(
  636. "SELECT CONSTRAINT_NAME
  637. FROM information_schema.KEY_COLUMN_USAGE
  638. WHERE TABLE_SCHEMA = CURRENT_SCHEMA()
  639. AND TABLE_NAME IS NOT NULL
  640. AND TABLE_NAME = '%s'
  641. AND COLUMN_NAME = '%s'
  642. ORDER BY POSITION_IN_UNIQUE_CONSTRAINT",
  643. $tableName,
  644. $column
  645. ));
  646. foreach ($rows as $row) {
  647. $this->dropForeignKey($tableName, $columns, $row['constraint_name']);
  648. }
  649. }
  650. }
  651. $this->endCommandTimer();
  652. }
  653. /**
  654. * {@inheritdoc}
  655. */
  656. public function getSqlType($type, $limit = null)
  657. {
  658. switch ($type) {
  659. case static::PHINX_TYPE_INTEGER:
  660. if ($limit && $limit == static::INT_SMALL) {
  661. return array(
  662. 'name' => 'smallint',
  663. 'limit' => static::INT_SMALL
  664. );
  665. }
  666. return array('name' => $type);
  667. case static::PHINX_TYPE_TEXT:
  668. case static::PHINX_TYPE_TIME:
  669. case static::PHINX_TYPE_DATE:
  670. case static::PHINX_TYPE_BOOLEAN:
  671. case static::PHINX_TYPE_JSON:
  672. case static::PHINX_TYPE_JSONB:
  673. case static::PHINX_TYPE_UUID:
  674. return array('name' => $type);
  675. case static::PHINX_TYPE_DECIMAL:
  676. return array('name' => $type, 'precision' => 18, 'scale' => 0);
  677. case static::PHINX_TYPE_STRING:
  678. return array('name' => 'character varying', 'limit' => 255);
  679. case static::PHINX_TYPE_CHAR:
  680. return array('name' => 'character', 'limit' => 255);
  681. case static::PHINX_TYPE_BIG_INTEGER:
  682. return array('name' => 'bigint');
  683. case static::PHINX_TYPE_FLOAT:
  684. return array('name' => 'real');
  685. case static::PHINX_TYPE_DATETIME:
  686. case static::PHINX_TYPE_TIMESTAMP:
  687. return array('name' => 'timestamp');
  688. case static::PHINX_TYPE_BLOB:
  689. case static::PHINX_TYPE_BINARY:
  690. return array('name' => 'bytea');
  691. // Geospatial database types
  692. // Spatial storage in Postgres is done via the PostGIS extension,
  693. // which enables the use of the "geography" type in combination
  694. // with SRID 4326.
  695. case static::PHINX_TYPE_GEOMETRY:
  696. return array('name' => 'geography', 'geometry', 4326);
  697. break;
  698. case static::PHINX_TYPE_POINT:
  699. return array('name' => 'geography', 'point', 4326);
  700. break;
  701. case static::PHINX_TYPE_LINESTRING:
  702. return array('name' => 'geography', 'linestring', 4326);
  703. break;
  704. case static::PHINX_TYPE_POLYGON:
  705. return array('name' => 'geography', 'polygon', 4326);
  706. break;
  707. default:
  708. if ($this->isArrayType($type)) {
  709. return array('name' => $type);
  710. }
  711. // Return array type
  712. throw new \RuntimeException('The type: "' . $type . '" is not supported');
  713. }
  714. }
  715. /**
  716. * Returns Phinx type by SQL type
  717. *
  718. * @param string $sqlType SQL type
  719. * @returns string Phinx type
  720. */
  721. public function getPhinxType($sqlType)
  722. {
  723. switch ($sqlType) {
  724. case 'character varying':
  725. case 'varchar':
  726. return static::PHINX_TYPE_STRING;
  727. case 'character':
  728. case 'char':
  729. return static::PHINX_TYPE_CHAR;
  730. case 'text':
  731. return static::PHINX_TYPE_TEXT;
  732. case 'json':
  733. return static::PHINX_TYPE_JSON;
  734. case 'jsonb':
  735. return static::PHINX_TYPE_JSONB;
  736. case 'smallint':
  737. return array(
  738. 'name' => 'smallint',
  739. 'limit' => static::INT_SMALL
  740. );
  741. case 'int':
  742. case 'int4':
  743. case 'integer':
  744. return static::PHINX_TYPE_INTEGER;
  745. case 'decimal':
  746. case 'numeric':
  747. return static::PHINX_TYPE_DECIMAL;
  748. case 'bigint':
  749. case 'int8':
  750. return static::PHINX_TYPE_BIG_INTEGER;
  751. case 'real':
  752. case 'float4':
  753. return static::PHINX_TYPE_FLOAT;
  754. case 'bytea':
  755. return static::PHINX_TYPE_BINARY;
  756. break;
  757. case 'time':
  758. case 'timetz':
  759. case 'time with time zone':
  760. case 'time without time zone':
  761. return static::PHINX_TYPE_TIME;
  762. case 'date':
  763. return static::PHINX_TYPE_DATE;
  764. case 'timestamp':
  765. case 'timestamptz':
  766. case 'timestamp with time zone':
  767. case 'timestamp without time zone':
  768. return static::PHINX_TYPE_DATETIME;
  769. case 'bool':
  770. case 'boolean':
  771. return static::PHINX_TYPE_BOOLEAN;
  772. case 'uuid':
  773. return static::PHINX_TYPE_UUID;
  774. default:
  775. throw new \RuntimeException('The PostgreSQL type: "' . $sqlType . '" is not supported');
  776. }
  777. }
  778. /**
  779. * {@inheritdoc}
  780. */
  781. public function createDatabase($name, $options = array())
  782. {
  783. $this->startCommandTimer();
  784. $this->writeCommand('createDatabase', array($name));
  785. $charset = isset($options['charset']) ? $options['charset'] : 'utf8';
  786. $this->execute(sprintf("CREATE DATABASE %s WITH ENCODING = '%s'", $name, $charset));
  787. $this->endCommandTimer();
  788. }
  789. /**
  790. * {@inheritdoc}
  791. */
  792. public function hasDatabase($databaseName)
  793. {
  794. $sql = sprintf("SELECT count(*) FROM pg_database WHERE datname = '%s'", $databaseName);
  795. $result = $this->fetchRow($sql);
  796. return $result['count'] > 0;
  797. }
  798. /**
  799. * {@inheritdoc}
  800. */
  801. public function dropDatabase($name)
  802. {
  803. $this->startCommandTimer();
  804. $this->writeCommand('dropDatabase', array($name));
  805. $this->disconnect();
  806. $this->execute(sprintf('DROP DATABASE IF EXISTS %s', $name));
  807. $this->connect();
  808. $this->endCommandTimer();
  809. }
  810. /**
  811. * Get the defintion for a `DEFAULT` statement.
  812. *
  813. * @param mixed $default
  814. * @return string
  815. */
  816. protected function getDefaultValueDefinition($default)
  817. {
  818. if (is_string($default) && 'CURRENT_TIMESTAMP' !== $default) {
  819. $default = $this->getConnection()->quote($default);
  820. } elseif (is_bool($default)) {
  821. $default = $this->castToBool($default);
  822. }
  823. return isset($default) ? 'DEFAULT ' . $default : '';
  824. }
  825. /**
  826. * Gets the PostgreSQL Column Definition for a Column object.
  827. *
  828. * @param Column $column Column
  829. * @return string
  830. */
  831. protected function getColumnSqlDefinition(Column $column)
  832. {
  833. $buffer = array();
  834. if ($column->isIdentity()) {
  835. $buffer[] = $column->getType() == 'biginteger' ? 'BIGSERIAL' : 'SERIAL';
  836. } else {
  837. $sqlType = $this->getSqlType($column->getType(), $column->getLimit());
  838. $buffer[] = strtoupper($sqlType['name']);
  839. // integers cant have limits in postgres
  840. if (static::PHINX_TYPE_DECIMAL === $sqlType['name'] && ($column->getPrecision() || $column->getScale())) {
  841. $buffer[] = sprintf(
  842. '(%s, %s)',
  843. $column->getPrecision() ? $column->getPrecision() : $sqlType['precision'],
  844. $column->getScale() ? $column->getScale() : $sqlType['scale']
  845. );
  846. } elseif (!in_array($sqlType['name'], array('integer', 'smallint'))) {
  847. if ($column->getLimit() || isset($sqlType['limit'])) {
  848. $buffer[] = sprintf('(%s)', $column->getLimit() ? $column->getLimit() : $sqlType['limit']);
  849. }
  850. }
  851. $timeTypes = array(
  852. 'time',
  853. 'timestamp',
  854. );
  855. if (in_array($sqlType['name'], $timeTypes) && $column->isTimezone()) {
  856. $buffer[] = strtoupper('with time zone');
  857. }
  858. }
  859. $buffer[] = $column->isNull() ? 'NULL' : 'NOT NULL';
  860. if (!is_null($column->getDefault())) {
  861. $buffer[] = $this->getDefaultValueDefinition($column->getDefault());
  862. }
  863. return implode(' ', $buffer);
  864. }
  865. /**
  866. * Gets the PostgreSQL Column Comment Defininition for a column object.
  867. *
  868. * @param Column $column Column
  869. * @param string $tableName Table name
  870. * @return string
  871. */
  872. protected function getColumnCommentSqlDefinition(Column $column, $tableName)
  873. {
  874. // passing 'null' is to remove column comment
  875. $comment = (strcasecmp($column->getComment(), 'NULL') !== 0)
  876. ? $this->getConnection()->quote($column->getComment())
  877. : 'NULL';
  878. return sprintf(
  879. 'COMMENT ON COLUMN %s.%s IS %s;',
  880. $tableName,
  881. $column->getName(),
  882. $comment
  883. );
  884. }
  885. /**
  886. * Gets the PostgreSQL Index Definition for an Index object.
  887. *
  888. * @param Index $index Index
  889. * @param string $tableName Table name
  890. * @return string
  891. */
  892. protected function getIndexSqlDefinition(Index $index, $tableName)
  893. {
  894. if (is_string($index->getName())) {
  895. $indexName = $index->getName();
  896. } else {
  897. $columnNames = $index->getColumns();
  898. if (is_string($columnNames)) {
  899. $columnNames = array($columnNames);
  900. }
  901. $indexName = sprintf('%s_%s', $tableName, implode('_', $columnNames));
  902. }
  903. $def = sprintf(
  904. "CREATE %s INDEX %s ON %s (%s);",
  905. ($index->getType() === Index::UNIQUE ? 'UNIQUE' : ''),
  906. $indexName,
  907. $this->quoteTableName($tableName),
  908. implode(',', $index->getColumns())
  909. );
  910. return $def;
  911. }
  912. /**
  913. * Gets the MySQL Foreign Key Definition for an ForeignKey object.
  914. *
  915. * @param ForeignKey $foreignKey
  916. * @param string $tableName Table name
  917. * @return string
  918. */
  919. protected function getForeignKeySqlDefinition(ForeignKey $foreignKey, $tableName)
  920. {
  921. $constraintName = $foreignKey->getConstraint() ?: $tableName . '_' . implode('_', $foreignKey->getColumns());
  922. $def = ' CONSTRAINT "' . $constraintName . '" FOREIGN KEY ("' . implode('", "', $foreignKey->getColumns()) . '")';
  923. $def .= " REFERENCES {$this->quoteTableName($foreignKey->getReferencedTable()->getName())} (\"" . implode('", "', $foreignKey->getReferencedColumns()) . '")';
  924. if ($foreignKey->getOnDelete()) {
  925. $def .= " ON DELETE {$foreignKey->getOnDelete()}";
  926. }
  927. if ($foreignKey->getOnUpdate()) {
  928. $def .= " ON UPDATE {$foreignKey->getOnUpdate()}";
  929. }
  930. return $def;
  931. }
  932. /**
  933. * {@inheritdoc}
  934. */
  935. public function createSchemaTable()
  936. {
  937. // Create the public/custom schema if it doesn't already exist
  938. if (false === $this->hasSchema($this->getSchemaName())) {
  939. $this->createSchema($this->getSchemaName());
  940. }
  941. $this->fetchAll(sprintf('SET search_path TO %s', $this->getSchemaName()));
  942. return parent::createSchemaTable();
  943. }
  944. /**
  945. * Creates the specified schema.
  946. *
  947. * @param string $schemaName Schema Name
  948. * @return void
  949. */
  950. public function createSchema($schemaName = 'public')
  951. {
  952. $this->startCommandTimer();
  953. $this->writeCommand('addSchema', array($schemaName));
  954. $sql = sprintf('CREATE SCHEMA %s;', $this->quoteSchemaName($schemaName)); // from postgres 9.3 we can use "CREATE SCHEMA IF NOT EXISTS schema_name"
  955. $this->execute($sql);
  956. $this->endCommandTimer();
  957. }
  958. /**
  959. * Checks to see if a schema exists.
  960. *
  961. * @param string $schemaName Schema Name
  962. * @return boolean
  963. */
  964. public function hasSchema($schemaName)
  965. {
  966. $sql = sprintf(
  967. "SELECT count(*)
  968. FROM pg_namespace
  969. WHERE nspname = '%s'",
  970. $schemaName
  971. );
  972. $result = $this->fetchRow($sql);
  973. return $result['count'] > 0;
  974. }
  975. /**
  976. * Drops the specified schema table.
  977. *
  978. * @param string $schemaName Schema name
  979. * @return void
  980. */
  981. public function dropSchema($schemaName)
  982. {
  983. $this->startCommandTimer();
  984. $this->writeCommand('dropSchema', array($schemaName));
  985. $sql = sprintf("DROP SCHEMA IF EXISTS %s CASCADE;", $this->quoteSchemaName($schemaName));
  986. $this->execute($sql);
  987. $this->endCommandTimer();
  988. }
  989. /**
  990. * Drops all schemas.
  991. *
  992. * @return void
  993. */
  994. public function dropAllSchemas()
  995. {
  996. $this->startCommandTimer();
  997. $this->writeCommand('dropAllSchemas');
  998. foreach ($this->getAllSchemas() as $schema) {
  999. $this->dropSchema($schema);
  1000. }
  1001. $this->endCommandTimer();
  1002. }
  1003. /**
  1004. * Returns schemas.
  1005. *
  1006. * @return array
  1007. */
  1008. public function getAllSchemas()
  1009. {
  1010. $sql = "SELECT schema_name
  1011. FROM information_schema.schemata
  1012. WHERE schema_name <> 'information_schema' AND schema_name !~ '^pg_'";
  1013. $items = $this->fetchAll($sql);
  1014. $schemaNames = array();
  1015. foreach ($items as $item) {
  1016. $schemaNames[] = $item['schema_name'];
  1017. }
  1018. return $schemaNames;
  1019. }
  1020. /**
  1021. * {@inheritdoc}
  1022. */
  1023. public function getColumnTypes()
  1024. {
  1025. return array_merge(parent::getColumnTypes(), array('json', 'jsonb'));
  1026. }
  1027. /**
  1028. * {@inheritdoc}
  1029. */
  1030. public function isValidColumnType(Column $column)
  1031. {
  1032. // If not a standard column type, maybe it is array type?
  1033. return (parent::isValidColumnType($column) || $this->isArrayType($column->getType()));
  1034. }
  1035. /**
  1036. * Check if the given column is an array of a valid type.
  1037. *
  1038. * @param string $columnType
  1039. * @return bool
  1040. */
  1041. protected function isArrayType($columnType)
  1042. {
  1043. if (!preg_match('/^([a-z]+)(?:\[\]){1,}$/', $columnType, $matches)) {
  1044. return false;
  1045. }
  1046. $baseType = $matches[1];
  1047. return in_array($baseType, $this->getColumnTypes());
  1048. }
  1049. /**
  1050. * Gets the schema name.
  1051. *
  1052. * @return string
  1053. */
  1054. private function getSchemaName()
  1055. {
  1056. $options = $this->getOptions();
  1057. return empty($options['schema']) ? 'public' : $options['schema'];
  1058. }
  1059. /**
  1060. * Cast a value to a boolean appropriate for the adapter.
  1061. *
  1062. * @param mixed $value The value to be cast
  1063. *
  1064. * @return mixed
  1065. */
  1066. public function castToBool($value)
  1067. {
  1068. return (bool) $value ? 'TRUE' : 'FALSE';
  1069. }
  1070. }