PageRenderTime 130ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 1ms

/RestAPI/vendor/doctrine/dbal/lib/Doctrine/DBAL/Schema/PostgreSqlSchemaManager.php

https://gitlab.com/martinstti/silex-microframework-rest
PHP | 438 lines | 283 code | 54 blank | 101 comment | 36 complexity | d90f07c676438b3224e3c90331a302b2 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 MIT license. For more information, see
  17. * <http://www.doctrine-project.org>.
  18. */
  19. namespace Doctrine\DBAL\Schema;
  20. use Doctrine\DBAL\Exception\DriverException;
  21. use Doctrine\DBAL\Types\Type;
  22. /**
  23. * PostgreSQL Schema Manager.
  24. *
  25. * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
  26. * @author Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
  27. * @author Benjamin Eberlei <kontakt@beberlei.de>
  28. * @since 2.0
  29. */
  30. class PostgreSqlSchemaManager extends AbstractSchemaManager
  31. {
  32. /**
  33. * @var array
  34. */
  35. private $existingSchemaPaths;
  36. /**
  37. * Gets all the existing schema names.
  38. *
  39. * @return array
  40. */
  41. public function getSchemaNames()
  42. {
  43. $rows = $this->_conn->fetchAll("SELECT nspname as schema_name FROM pg_namespace WHERE nspname !~ '^pg_.*' and nspname != 'information_schema'");
  44. return array_map(function ($v) { return $v['schema_name']; }, $rows);
  45. }
  46. /**
  47. * Returns an array of schema search paths.
  48. *
  49. * This is a PostgreSQL only function.
  50. *
  51. * @return array
  52. */
  53. public function getSchemaSearchPaths()
  54. {
  55. $params = $this->_conn->getParams();
  56. $schema = explode(",", $this->_conn->fetchColumn('SHOW search_path'));
  57. if (isset($params['user'])) {
  58. $schema = str_replace('"$user"', $params['user'], $schema);
  59. }
  60. return array_map('trim', $schema);
  61. }
  62. /**
  63. * Gets names of all existing schemas in the current users search path.
  64. *
  65. * This is a PostgreSQL only function.
  66. *
  67. * @return array
  68. */
  69. public function getExistingSchemaSearchPaths()
  70. {
  71. if ($this->existingSchemaPaths === null) {
  72. $this->determineExistingSchemaSearchPaths();
  73. }
  74. return $this->existingSchemaPaths;
  75. }
  76. /**
  77. * Sets or resets the order of the existing schemas in the current search path of the user.
  78. *
  79. * This is a PostgreSQL only function.
  80. *
  81. * @return void
  82. */
  83. public function determineExistingSchemaSearchPaths()
  84. {
  85. $names = $this->getSchemaNames();
  86. $paths = $this->getSchemaSearchPaths();
  87. $this->existingSchemaPaths = array_filter($paths, function ($v) use ($names) {
  88. return in_array($v, $names);
  89. });
  90. }
  91. /**
  92. * {@inheritdoc}
  93. */
  94. public function dropDatabase($database)
  95. {
  96. try {
  97. parent::dropDatabase($database);
  98. } catch (DriverException $exception) {
  99. // If we have a SQLSTATE 55006, the drop database operation failed
  100. // because of active connections on the database.
  101. // To force dropping the database, we first have to close all active connections
  102. // on that database and issue the drop database operation again.
  103. if ($exception->getSQLState() !== '55006') {
  104. throw $exception;
  105. }
  106. $this->_execSql(
  107. array(
  108. $this->_platform->getDisallowDatabaseConnectionsSQL($database),
  109. $this->_platform->getCloseActiveDatabaseConnectionsSQL($database),
  110. )
  111. );
  112. parent::dropDatabase($database);
  113. }
  114. }
  115. /**
  116. * {@inheritdoc}
  117. */
  118. protected function _getPortableTableForeignKeyDefinition($tableForeignKey)
  119. {
  120. $onUpdate = null;
  121. $onDelete = null;
  122. if (preg_match('(ON UPDATE ([a-zA-Z0-9]+( (NULL|ACTION|DEFAULT))?))', $tableForeignKey['condef'], $match)) {
  123. $onUpdate = $match[1];
  124. }
  125. if (preg_match('(ON DELETE ([a-zA-Z0-9]+( (NULL|ACTION|DEFAULT))?))', $tableForeignKey['condef'], $match)) {
  126. $onDelete = $match[1];
  127. }
  128. if (preg_match('/FOREIGN KEY \((.+)\) REFERENCES (.+)\((.+)\)/', $tableForeignKey['condef'], $values)) {
  129. // PostgreSQL returns identifiers that are keywords with quotes, we need them later, don't get
  130. // the idea to trim them here.
  131. $localColumns = array_map('trim', explode(",", $values[1]));
  132. $foreignColumns = array_map('trim', explode(",", $values[3]));
  133. $foreignTable = $values[2];
  134. }
  135. return new ForeignKeyConstraint(
  136. $localColumns, $foreignTable, $foreignColumns, $tableForeignKey['conname'],
  137. array('onUpdate' => $onUpdate, 'onDelete' => $onDelete)
  138. );
  139. }
  140. /**
  141. * {@inheritdoc}
  142. */
  143. protected function _getPortableTriggerDefinition($trigger)
  144. {
  145. return $trigger['trigger_name'];
  146. }
  147. /**
  148. * {@inheritdoc}
  149. */
  150. protected function _getPortableViewDefinition($view)
  151. {
  152. return new View($view['schemaname'].'.'.$view['viewname'], $view['definition']);
  153. }
  154. /**
  155. * {@inheritdoc}
  156. */
  157. protected function _getPortableUserDefinition($user)
  158. {
  159. return array(
  160. 'user' => $user['usename'],
  161. 'password' => $user['passwd']
  162. );
  163. }
  164. /**
  165. * {@inheritdoc}
  166. */
  167. protected function _getPortableTableDefinition($table)
  168. {
  169. $schemas = $this->getExistingSchemaSearchPaths();
  170. $firstSchema = array_shift($schemas);
  171. if ($table['schema_name'] == $firstSchema) {
  172. return $table['table_name'];
  173. } else {
  174. return $table['schema_name'] . "." . $table['table_name'];
  175. }
  176. }
  177. /**
  178. * {@inheritdoc}
  179. *
  180. * @license New BSD License
  181. * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
  182. */
  183. protected function _getPortableTableIndexesList($tableIndexes, $tableName=null)
  184. {
  185. $buffer = array();
  186. foreach ($tableIndexes as $row) {
  187. $colNumbers = explode(' ', $row['indkey']);
  188. $colNumbersSql = 'IN (' . join(' ,', $colNumbers) . ' )';
  189. $columnNameSql = "SELECT attnum, attname FROM pg_attribute
  190. WHERE attrelid={$row['indrelid']} AND attnum $colNumbersSql ORDER BY attnum ASC;";
  191. $stmt = $this->_conn->executeQuery($columnNameSql);
  192. $indexColumns = $stmt->fetchAll();
  193. // required for getting the order of the columns right.
  194. foreach ($colNumbers as $colNum) {
  195. foreach ($indexColumns as $colRow) {
  196. if ($colNum == $colRow['attnum']) {
  197. $buffer[] = array(
  198. 'key_name' => $row['relname'],
  199. 'column_name' => trim($colRow['attname']),
  200. 'non_unique' => !$row['indisunique'],
  201. 'primary' => $row['indisprimary'],
  202. 'where' => $row['where'],
  203. );
  204. }
  205. }
  206. }
  207. }
  208. return parent::_getPortableTableIndexesList($buffer, $tableName);
  209. }
  210. /**
  211. * {@inheritdoc}
  212. */
  213. protected function _getPortableDatabaseDefinition($database)
  214. {
  215. return $database['datname'];
  216. }
  217. /**
  218. * {@inheritdoc}
  219. */
  220. protected function _getPortableSequencesList($sequences)
  221. {
  222. $sequenceDefinitions = array();
  223. foreach ($sequences as $sequence) {
  224. if ($sequence['schemaname'] != 'public') {
  225. $sequenceName = $sequence['schemaname'] . "." . $sequence['relname'];
  226. } else {
  227. $sequenceName = $sequence['relname'];
  228. }
  229. $sequenceDefinitions[$sequenceName] = $sequence;
  230. }
  231. $list = array();
  232. foreach ($this->filterAssetNames(array_keys($sequenceDefinitions)) as $sequenceName) {
  233. $list[] = $this->_getPortableSequenceDefinition($sequenceDefinitions[$sequenceName]);
  234. }
  235. return $list;
  236. }
  237. /**
  238. * {@inheritdoc}
  239. */
  240. protected function getPortableNamespaceDefinition(array $namespace)
  241. {
  242. return $namespace['nspname'];
  243. }
  244. /**
  245. * {@inheritdoc}
  246. */
  247. protected function _getPortableSequenceDefinition($sequence)
  248. {
  249. if ($sequence['schemaname'] != 'public') {
  250. $sequenceName = $sequence['schemaname'] . "." . $sequence['relname'];
  251. } else {
  252. $sequenceName = $sequence['relname'];
  253. }
  254. $data = $this->_conn->fetchAll('SELECT min_value, increment_by FROM ' . $this->_platform->quoteIdentifier($sequenceName));
  255. return new Sequence($sequenceName, $data[0]['increment_by'], $data[0]['min_value']);
  256. }
  257. /**
  258. * {@inheritdoc}
  259. */
  260. protected function _getPortableTableColumnDefinition($tableColumn)
  261. {
  262. $tableColumn = array_change_key_case($tableColumn, CASE_LOWER);
  263. if (strtolower($tableColumn['type']) === 'varchar' || strtolower($tableColumn['type']) === 'bpchar') {
  264. // get length from varchar definition
  265. $length = preg_replace('~.*\(([0-9]*)\).*~', '$1', $tableColumn['complete_type']);
  266. $tableColumn['length'] = $length;
  267. }
  268. $matches = array();
  269. $autoincrement = false;
  270. if (preg_match("/^nextval\('(.*)'(::.*)?\)$/", $tableColumn['default'], $matches)) {
  271. $tableColumn['sequence'] = $matches[1];
  272. $tableColumn['default'] = null;
  273. $autoincrement = true;
  274. }
  275. if (preg_match("/^'(.*)'::.*$/", $tableColumn['default'], $matches)) {
  276. $tableColumn['default'] = $matches[1];
  277. }
  278. if (stripos($tableColumn['default'], 'NULL') === 0) {
  279. $tableColumn['default'] = null;
  280. }
  281. $length = (isset($tableColumn['length'])) ? $tableColumn['length'] : null;
  282. if ($length == '-1' && isset($tableColumn['atttypmod'])) {
  283. $length = $tableColumn['atttypmod'] - 4;
  284. }
  285. if ((int) $length <= 0) {
  286. $length = null;
  287. }
  288. $fixed = null;
  289. if (!isset($tableColumn['name'])) {
  290. $tableColumn['name'] = '';
  291. }
  292. $precision = null;
  293. $scale = null;
  294. $dbType = strtolower($tableColumn['type']);
  295. if (strlen($tableColumn['domain_type']) && !$this->_platform->hasDoctrineTypeMappingFor($tableColumn['type'])) {
  296. $dbType = strtolower($tableColumn['domain_type']);
  297. $tableColumn['complete_type'] = $tableColumn['domain_complete_type'];
  298. }
  299. $type = $this->_platform->getDoctrineTypeMapping($dbType);
  300. $type = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
  301. $tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);
  302. switch ($dbType) {
  303. case 'smallint':
  304. case 'int2':
  305. $length = null;
  306. break;
  307. case 'int':
  308. case 'int4':
  309. case 'integer':
  310. $length = null;
  311. break;
  312. case 'bigint':
  313. case 'int8':
  314. $length = null;
  315. break;
  316. case 'bool':
  317. case 'boolean':
  318. if ($tableColumn['default'] === 'true') {
  319. $tableColumn['default'] = true;
  320. }
  321. if ($tableColumn['default'] === 'false') {
  322. $tableColumn['default'] = false;
  323. }
  324. $length = null;
  325. break;
  326. case 'text':
  327. $fixed = false;
  328. break;
  329. case 'varchar':
  330. case 'interval':
  331. case '_varchar':
  332. $fixed = false;
  333. break;
  334. case 'char':
  335. case 'bpchar':
  336. $fixed = true;
  337. break;
  338. case 'float':
  339. case 'float4':
  340. case 'float8':
  341. case 'double':
  342. case 'double precision':
  343. case 'real':
  344. case 'decimal':
  345. case 'money':
  346. case 'numeric':
  347. if (preg_match('([A-Za-z]+\(([0-9]+)\,([0-9]+)\))', $tableColumn['complete_type'], $match)) {
  348. $precision = $match[1];
  349. $scale = $match[2];
  350. $length = null;
  351. }
  352. break;
  353. case 'year':
  354. $length = null;
  355. break;
  356. }
  357. if ($tableColumn['default'] && preg_match("('([^']+)'::)", $tableColumn['default'], $match)) {
  358. $tableColumn['default'] = $match[1];
  359. }
  360. $options = array(
  361. 'length' => $length,
  362. 'notnull' => (bool) $tableColumn['isnotnull'],
  363. 'default' => $tableColumn['default'],
  364. 'primary' => (bool) ($tableColumn['pri'] == 't'),
  365. 'precision' => $precision,
  366. 'scale' => $scale,
  367. 'fixed' => $fixed,
  368. 'unsigned' => false,
  369. 'autoincrement' => $autoincrement,
  370. 'comment' => isset($tableColumn['comment']) && $tableColumn['comment'] !== ''
  371. ? $tableColumn['comment']
  372. : null,
  373. );
  374. $column = new Column($tableColumn['field'], Type::getType($type), $options);
  375. if (isset($tableColumn['collation']) && !empty($tableColumn['collation'])) {
  376. $column->setPlatformOption('collation', $tableColumn['collation']);
  377. }
  378. return $column;
  379. }
  380. }