PageRenderTime 60ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/php/main/inc/lib/symfony/Doctrine/DBAL/Schema/PostgreSqlSchemaManager.php

https://bitbucket.org/frchico/chamilo_openshift
PHP | 359 lines | 250 code | 43 blank | 66 comment | 27 complexity | 57ed5ee4969d786c0b22cd5abce5c7d7 MD5 | raw file
  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. * PostgreSQL Schema Manager
  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. * @since 2.0
  28. */
  29. class PostgreSqlSchemaManager extends AbstractSchemaManager
  30. {
  31. /**
  32. * @var array
  33. */
  34. private $existingSchemaPaths;
  35. /**
  36. * Get all the existing schema names.
  37. *
  38. * @return array
  39. */
  40. public function getSchemaNames()
  41. {
  42. $rows = $this->_conn->fetchAll('SELECT schema_name FROM information_schema.schemata');
  43. return array_map(function($v) { return $v['schema_name']; }, $rows);
  44. }
  45. /**
  46. * Return an array of schema search paths
  47. *
  48. * This is a PostgreSQL only function.
  49. *
  50. * @return array
  51. */
  52. public function getSchemaSearchPaths()
  53. {
  54. $params = $this->_conn->getParams();
  55. $schema = explode(",", $this->_conn->fetchColumn('SHOW search_path'));
  56. if (isset($params['user'])) {
  57. $schema = str_replace('"$user"', $params['user'], $schema);
  58. }
  59. return $schema;
  60. }
  61. /**
  62. * Get names of all existing schemas in the current users search path.
  63. *
  64. * This is a PostgreSQL only function.
  65. *
  66. * @return array
  67. */
  68. public function getExistingSchemaSearchPaths()
  69. {
  70. if ($this->existingSchemaPaths === null) {
  71. $this->determineExistingSchemaSearchPaths();
  72. }
  73. return $this->existingSchemaPaths;
  74. }
  75. /**
  76. * Use this to set or reset the order of the existing schemas in the current search path of the user
  77. *
  78. * This is a PostgreSQL only function.
  79. *
  80. * @return type
  81. */
  82. public function determineExistingSchemaSearchPaths()
  83. {
  84. $names = $this->getSchemaNames();
  85. $paths = $this->getSchemaSearchPaths();
  86. $this->existingSchemaPaths = array_filter($paths, function ($v) use ($names) {
  87. return in_array($v, $names);
  88. });
  89. }
  90. protected function _getPortableTableForeignKeyDefinition($tableForeignKey)
  91. {
  92. $onUpdate = null;
  93. $onDelete = null;
  94. if (preg_match('(ON UPDATE ([a-zA-Z0-9]+( (NULL|ACTION|DEFAULT))?))', $tableForeignKey['condef'], $match)) {
  95. $onUpdate = $match[1];
  96. }
  97. if (preg_match('(ON DELETE ([a-zA-Z0-9]+( (NULL|ACTION|DEFAULT))?))', $tableForeignKey['condef'], $match)) {
  98. $onDelete = $match[1];
  99. }
  100. if (preg_match('/FOREIGN KEY \((.+)\) REFERENCES (.+)\((.+)\)/', $tableForeignKey['condef'], $values)) {
  101. // PostgreSQL returns identifiers that are keywords with quotes, we need them later, don't get
  102. // the idea to trim them here.
  103. $localColumns = array_map('trim', explode(",", $values[1]));
  104. $foreignColumns = array_map('trim', explode(",", $values[3]));
  105. $foreignTable = $values[2];
  106. }
  107. return new ForeignKeyConstraint(
  108. $localColumns, $foreignTable, $foreignColumns, $tableForeignKey['conname'],
  109. array('onUpdate' => $onUpdate, 'onDelete' => $onDelete)
  110. );
  111. }
  112. public function dropDatabase($database)
  113. {
  114. $params = $this->_conn->getParams();
  115. $params["dbname"] = "postgres";
  116. $tmpPlatform = $this->_platform;
  117. $tmpConn = $this->_conn;
  118. $this->_conn = \Doctrine\DBAL\DriverManager::getConnection($params);
  119. $this->_platform = $this->_conn->getDatabasePlatform();
  120. parent::dropDatabase($database);
  121. $this->_platform = $tmpPlatform;
  122. $this->_conn = $tmpConn;
  123. }
  124. public function createDatabase($database)
  125. {
  126. $params = $this->_conn->getParams();
  127. $params["dbname"] = "postgres";
  128. $tmpPlatform = $this->_platform;
  129. $tmpConn = $this->_conn;
  130. $this->_conn = \Doctrine\DBAL\DriverManager::getConnection($params);
  131. $this->_platform = $this->_conn->getDatabasePlatform();
  132. parent::createDatabase($database);
  133. $this->_platform = $tmpPlatform;
  134. $this->_conn = $tmpConn;
  135. }
  136. protected function _getPortableTriggerDefinition($trigger)
  137. {
  138. return $trigger['trigger_name'];
  139. }
  140. protected function _getPortableViewDefinition($view)
  141. {
  142. return new View($view['viewname'], $view['definition']);
  143. }
  144. protected function _getPortableUserDefinition($user)
  145. {
  146. return array(
  147. 'user' => $user['usename'],
  148. 'password' => $user['passwd']
  149. );
  150. }
  151. protected function _getPortableTableDefinition($table)
  152. {
  153. $schemas = $this->getExistingSchemaSearchPaths();
  154. $firstSchema = array_shift($schemas);
  155. if ($table['schema_name'] == $firstSchema) {
  156. return $table['table_name'];
  157. } else {
  158. return $table['schema_name'] . "." . $table['table_name'];
  159. }
  160. }
  161. /**
  162. * @license New BSD License
  163. * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
  164. * @param array $tableIndexes
  165. * @param string $tableName
  166. * @return array
  167. */
  168. protected function _getPortableTableIndexesList($tableIndexes, $tableName=null)
  169. {
  170. $buffer = array();
  171. foreach ($tableIndexes AS $row) {
  172. $colNumbers = explode(' ', $row['indkey']);
  173. $colNumbersSql = 'IN (' . join(' ,', $colNumbers) . ' )';
  174. $columnNameSql = "SELECT attnum, attname FROM pg_attribute
  175. WHERE attrelid={$row['indrelid']} AND attnum $colNumbersSql ORDER BY attnum ASC;";
  176. $stmt = $this->_conn->executeQuery($columnNameSql);
  177. $indexColumns = $stmt->fetchAll();
  178. // required for getting the order of the columns right.
  179. foreach ($colNumbers AS $colNum) {
  180. foreach ($indexColumns as $colRow) {
  181. if ($colNum == $colRow['attnum']) {
  182. $buffer[] = array(
  183. 'key_name' => $row['relname'],
  184. 'column_name' => trim($colRow['attname']),
  185. 'non_unique' => !$row['indisunique'],
  186. 'primary' => $row['indisprimary']
  187. );
  188. }
  189. }
  190. }
  191. }
  192. return parent::_getPortableTableIndexesList($buffer, $tableName);
  193. }
  194. protected function _getPortableDatabaseDefinition($database)
  195. {
  196. return $database['datname'];
  197. }
  198. protected function _getPortableSequenceDefinition($sequence)
  199. {
  200. if ($sequence['schemaname'] != 'public') {
  201. $sequenceName = $sequence['schemaname'] . "." . $sequence['relname'];
  202. } else {
  203. $sequenceName = $sequence['relname'];
  204. }
  205. $data = $this->_conn->fetchAll('SELECT min_value, increment_by FROM ' . $sequenceName);
  206. return new Sequence($sequenceName, $data[0]['increment_by'], $data[0]['min_value']);
  207. }
  208. protected function _getPortableTableColumnDefinition($tableColumn)
  209. {
  210. $tableColumn = array_change_key_case($tableColumn, CASE_LOWER);
  211. if (strtolower($tableColumn['type']) === 'varchar') {
  212. // get length from varchar definition
  213. $length = preg_replace('~.*\(([0-9]*)\).*~', '$1', $tableColumn['complete_type']);
  214. $tableColumn['length'] = $length;
  215. }
  216. $matches = array();
  217. $autoincrement = false;
  218. if (preg_match("/^nextval\('(.*)'(::.*)?\)$/", $tableColumn['default'], $matches)) {
  219. $tableColumn['sequence'] = $matches[1];
  220. $tableColumn['default'] = null;
  221. $autoincrement = true;
  222. }
  223. if (stripos($tableColumn['default'], 'NULL') === 0) {
  224. $tableColumn['default'] = null;
  225. }
  226. $length = (isset($tableColumn['length'])) ? $tableColumn['length'] : null;
  227. if ($length == '-1' && isset($tableColumn['atttypmod'])) {
  228. $length = $tableColumn['atttypmod'] - 4;
  229. }
  230. if ((int) $length <= 0) {
  231. $length = null;
  232. }
  233. $fixed = null;
  234. if (!isset($tableColumn['name'])) {
  235. $tableColumn['name'] = '';
  236. }
  237. $precision = null;
  238. $scale = null;
  239. $dbType = strtolower($tableColumn['type']);
  240. if (strlen($tableColumn['domain_type']) && !$this->_platform->hasDoctrineTypeMappingFor($tableColumn['type'])) {
  241. $dbType = strtolower($tableColumn['domain_type']);
  242. $tableColumn['complete_type'] = $tableColumn['domain_complete_type'];
  243. }
  244. $type = $this->_platform->getDoctrineTypeMapping($dbType);
  245. $type = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
  246. $tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);
  247. switch ($dbType) {
  248. case 'smallint':
  249. case 'int2':
  250. $length = null;
  251. break;
  252. case 'int':
  253. case 'int4':
  254. case 'integer':
  255. $length = null;
  256. break;
  257. case 'bigint':
  258. case 'int8':
  259. $length = null;
  260. break;
  261. case 'bool':
  262. case 'boolean':
  263. $length = null;
  264. break;
  265. case 'text':
  266. $fixed = false;
  267. break;
  268. case 'varchar':
  269. case 'interval':
  270. case '_varchar':
  271. $fixed = false;
  272. break;
  273. case 'char':
  274. case 'bpchar':
  275. $fixed = true;
  276. break;
  277. case 'float':
  278. case 'float4':
  279. case 'float8':
  280. case 'double':
  281. case 'double precision':
  282. case 'real':
  283. case 'decimal':
  284. case 'money':
  285. case 'numeric':
  286. if (preg_match('([A-Za-z]+\(([0-9]+)\,([0-9]+)\))', $tableColumn['complete_type'], $match)) {
  287. $precision = $match[1];
  288. $scale = $match[2];
  289. $length = null;
  290. }
  291. break;
  292. case 'year':
  293. $length = null;
  294. break;
  295. }
  296. if ($tableColumn['default'] && preg_match("('([^']+)'::)", $tableColumn['default'], $match)) {
  297. $tableColumn['default'] = $match[1];
  298. }
  299. $options = array(
  300. 'length' => $length,
  301. 'notnull' => (bool) $tableColumn['isnotnull'],
  302. 'default' => $tableColumn['default'],
  303. 'primary' => (bool) ($tableColumn['pri'] == 't'),
  304. 'precision' => $precision,
  305. 'scale' => $scale,
  306. 'fixed' => $fixed,
  307. 'unsigned' => false,
  308. 'autoincrement' => $autoincrement,
  309. 'comment' => $tableColumn['comment'],
  310. );
  311. return new Column($tableColumn['field'], \Doctrine\DBAL\Types\Type::getType($type), $options);
  312. }
  313. }