PostgreSqlSchemaManager.php 9.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. <?php
  2. /*
  3. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14. *
  15. * This software consists of voluntary contributions made by many individuals
  16. * and is licensed under the LGPL. For more information, see
  17. * <http://www.doctrine-project.org>.
  18. */
  19. namespace Doctrine\DBAL\Schema;
  20. /**
  21. * xxx
  22. *
  23. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  24. * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
  25. * @author Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
  26. * @author Benjamin Eberlei <kontakt@beberlei.de>
  27. * @version $Revision$
  28. * @since 2.0
  29. */
  30. class PostgreSqlSchemaManager extends AbstractSchemaManager
  31. {
  32. protected function _getPortableTableForeignKeyDefinition($tableForeignKey)
  33. {
  34. $onUpdate = null;
  35. $onDelete = null;
  36. if (preg_match('(ON UPDATE ([a-zA-Z0-9]+))', $tableForeignKey['condef'], $match)) {
  37. $onUpdate = $match[1];
  38. }
  39. if (preg_match('(ON DELETE ([a-zA-Z0-9]+))', $tableForeignKey['condef'], $match)) {
  40. $onDelete = $match[1];
  41. }
  42. if (preg_match('/FOREIGN KEY \((.+)\) REFERENCES (.+)\((.+)\)/', $tableForeignKey['condef'], $values)) {
  43. // PostgreSQL returns identifiers that are keywords with quotes, we need them later, don't get
  44. // the idea to trim them here.
  45. $localColumns = array_map('trim', explode(",", $values[1]));
  46. $foreignColumns = array_map('trim', explode(",", $values[3]));
  47. $foreignTable = $values[2];
  48. }
  49. return new ForeignKeyConstraint(
  50. $localColumns, $foreignTable, $foreignColumns, $tableForeignKey['conname'],
  51. array('onUpdate' => $onUpdate, 'onDelete' => $onDelete)
  52. );
  53. }
  54. public function dropDatabase($database)
  55. {
  56. $params = $this->_conn->getParams();
  57. $params["dbname"] = "postgres";
  58. $tmpPlatform = $this->_platform;
  59. $tmpConn = $this->_conn;
  60. $this->_conn = \Doctrine\DBAL\DriverManager::getConnection($params);
  61. $this->_platform = $this->_conn->getDatabasePlatform();
  62. parent::dropDatabase($database);
  63. $this->_platform = $tmpPlatform;
  64. $this->_conn = $tmpConn;
  65. }
  66. public function createDatabase($database)
  67. {
  68. $params = $this->_conn->getParams();
  69. $params["dbname"] = "postgres";
  70. $tmpPlatform = $this->_platform;
  71. $tmpConn = $this->_conn;
  72. $this->_conn = \Doctrine\DBAL\DriverManager::getConnection($params);
  73. $this->_platform = $this->_conn->getDatabasePlatform();
  74. parent::createDatabase($database);
  75. $this->_platform = $tmpPlatform;
  76. $this->_conn = $tmpConn;
  77. }
  78. protected function _getPortableTriggerDefinition($trigger)
  79. {
  80. return $trigger['trigger_name'];
  81. }
  82. protected function _getPortableViewDefinition($view)
  83. {
  84. return new View($view['viewname'], $view['definition']);
  85. }
  86. protected function _getPortableUserDefinition($user)
  87. {
  88. return array(
  89. 'user' => $user['usename'],
  90. 'password' => $user['passwd']
  91. );
  92. }
  93. protected function _getPortableTableDefinition($table)
  94. {
  95. if ($table['schema_name'] == 'public') {
  96. return $table['table_name'];
  97. } else {
  98. return $table['schema_name'] . "." . $table['table_name'];
  99. }
  100. }
  101. /**
  102. * @license New BSD License
  103. * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
  104. * @param array $tableIndexes
  105. * @param string $tableName
  106. * @return array
  107. */
  108. protected function _getPortableTableIndexesList($tableIndexes, $tableName=null)
  109. {
  110. $buffer = array();
  111. foreach ($tableIndexes AS $row) {
  112. $colNumbers = explode(' ', $row['indkey']);
  113. $colNumbersSql = 'IN (' . join(' ,', $colNumbers) . ' )';
  114. $columnNameSql = "SELECT attnum, attname FROM pg_attribute
  115. WHERE attrelid={$row['indrelid']} AND attnum $colNumbersSql ORDER BY attnum ASC;";
  116. $stmt = $this->_conn->executeQuery($columnNameSql);
  117. $indexColumns = $stmt->fetchAll();
  118. // required for getting the order of the columns right.
  119. foreach ($colNumbers AS $colNum) {
  120. foreach ($indexColumns as $colRow) {
  121. if ($colNum == $colRow['attnum']) {
  122. $buffer[] = array(
  123. 'key_name' => $row['relname'],
  124. 'column_name' => trim($colRow['attname']),
  125. 'non_unique' => !$row['indisunique'],
  126. 'primary' => $row['indisprimary']
  127. );
  128. }
  129. }
  130. }
  131. }
  132. return parent::_getPortableTableIndexesList($buffer);
  133. }
  134. protected function _getPortableDatabaseDefinition($database)
  135. {
  136. return $database['datname'];
  137. }
  138. protected function _getPortableSequenceDefinition($sequence)
  139. {
  140. if ($sequence['schemaname'] != 'public') {
  141. $sequenceName = $sequence['schemaname'] . "." . $sequence['relname'];
  142. } else {
  143. $sequenceName = $sequence['relname'];
  144. }
  145. $data = $this->_conn->fetchAll('SELECT min_value, increment_by FROM ' . $sequenceName);
  146. return new Sequence($sequenceName, $data[0]['increment_by'], $data[0]['min_value']);
  147. }
  148. protected function _getPortableTableColumnDefinition($tableColumn)
  149. {
  150. $tableColumn = array_change_key_case($tableColumn, CASE_LOWER);
  151. if (strtolower($tableColumn['type']) === 'varchar') {
  152. // get length from varchar definition
  153. $length = preg_replace('~.*\(([0-9]*)\).*~', '$1', $tableColumn['complete_type']);
  154. $tableColumn['length'] = $length;
  155. }
  156. $matches = array();
  157. $autoincrement = false;
  158. if (preg_match("/^nextval\('(.*)'(::.*)?\)$/", $tableColumn['default'], $matches)) {
  159. $tableColumn['sequence'] = $matches[1];
  160. $tableColumn['default'] = null;
  161. $autoincrement = true;
  162. }
  163. if (stripos($tableColumn['default'], 'NULL') === 0) {
  164. $tableColumn['default'] = null;
  165. }
  166. $length = (isset($tableColumn['length'])) ? $tableColumn['length'] : null;
  167. if ($length == '-1' && isset($tableColumn['atttypmod'])) {
  168. $length = $tableColumn['atttypmod'] - 4;
  169. }
  170. if ((int) $length <= 0) {
  171. $length = null;
  172. }
  173. $fixed = null;
  174. if (!isset($tableColumn['name'])) {
  175. $tableColumn['name'] = '';
  176. }
  177. $precision = null;
  178. $scale = null;
  179. if ($this->_platform->hasDoctrineTypeMappingFor($tableColumn['type'])) {
  180. $dbType = strtolower($tableColumn['type']);
  181. } else {
  182. $dbType = strtolower($tableColumn['domain_type']);
  183. $tableColumn['complete_type'] = $tableColumn['domain_complete_type'];
  184. }
  185. $type = $this->_platform->getDoctrineTypeMapping($dbType);
  186. $type = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
  187. $tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);
  188. switch ($dbType) {
  189. case 'smallint':
  190. case 'int2':
  191. $length = null;
  192. break;
  193. case 'int':
  194. case 'int4':
  195. case 'integer':
  196. $length = null;
  197. break;
  198. case 'bigint':
  199. case 'int8':
  200. $length = null;
  201. break;
  202. case 'bool':
  203. case 'boolean':
  204. $length = null;
  205. break;
  206. case 'text':
  207. $fixed = false;
  208. break;
  209. case 'varchar':
  210. case 'interval':
  211. case '_varchar':
  212. $fixed = false;
  213. break;
  214. case 'char':
  215. case 'bpchar':
  216. $fixed = true;
  217. break;
  218. case 'float':
  219. case 'float4':
  220. case 'float8':
  221. case 'double':
  222. case 'double precision':
  223. case 'real':
  224. case 'decimal':
  225. case 'money':
  226. case 'numeric':
  227. if (preg_match('([A-Za-z]+\(([0-9]+)\,([0-9]+)\))', $tableColumn['complete_type'], $match)) {
  228. $precision = $match[1];
  229. $scale = $match[2];
  230. $length = null;
  231. }
  232. break;
  233. case 'year':
  234. $length = null;
  235. break;
  236. }
  237. $options = array(
  238. 'length' => $length,
  239. 'notnull' => (bool) $tableColumn['isnotnull'],
  240. 'default' => $tableColumn['default'],
  241. 'primary' => (bool) ($tableColumn['pri'] == 't'),
  242. 'precision' => $precision,
  243. 'scale' => $scale,
  244. 'fixed' => $fixed,
  245. 'unsigned' => false,
  246. 'autoincrement' => $autoincrement,
  247. 'comment' => $tableColumn['comment'],
  248. );
  249. return new Column($tableColumn['field'], \Doctrine\DBAL\Types\Type::getType($type), $options);
  250. }
  251. }