PageRenderTime 48ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://gitlab.com/koodersmiikka/operaatio-terveys
PHP | 410 lines | 265 code | 51 blank | 94 comment | 35 complexity | 0ff66351ef182125f4cac01f1a34dc2e 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\Types\Type;
  21. /**
  22. * PostgreSQL Schema Manager.
  23. *
  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. * Gets all the existing schema names.
  37. *
  38. * @return array
  39. */
  40. public function getSchemaNames()
  41. {
  42. $rows = $this->_conn->fetchAll("SELECT nspname as schema_name FROM pg_namespace WHERE nspname !~ '^pg_.*' and nspname != 'information_schema'");
  43. return array_map(function ($v) { return $v['schema_name']; }, $rows);
  44. }
  45. /**
  46. * Returns 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 array_map('trim', $schema);
  60. }
  61. /**
  62. * Gets 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. * Sets or resets 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 void
  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. /**
  91. * {@inheritdoc}
  92. */
  93. protected function _getPortableTableForeignKeyDefinition($tableForeignKey)
  94. {
  95. $onUpdate = null;
  96. $onDelete = null;
  97. if (preg_match('(ON UPDATE ([a-zA-Z0-9]+( (NULL|ACTION|DEFAULT))?))', $tableForeignKey['condef'], $match)) {
  98. $onUpdate = $match[1];
  99. }
  100. if (preg_match('(ON DELETE ([a-zA-Z0-9]+( (NULL|ACTION|DEFAULT))?))', $tableForeignKey['condef'], $match)) {
  101. $onDelete = $match[1];
  102. }
  103. if (preg_match('/FOREIGN KEY \((.+)\) REFERENCES (.+)\((.+)\)/', $tableForeignKey['condef'], $values)) {
  104. // PostgreSQL returns identifiers that are keywords with quotes, we need them later, don't get
  105. // the idea to trim them here.
  106. $localColumns = array_map('trim', explode(",", $values[1]));
  107. $foreignColumns = array_map('trim', explode(",", $values[3]));
  108. $foreignTable = $values[2];
  109. }
  110. return new ForeignKeyConstraint(
  111. $localColumns, $foreignTable, $foreignColumns, $tableForeignKey['conname'],
  112. array('onUpdate' => $onUpdate, 'onDelete' => $onDelete)
  113. );
  114. }
  115. /**
  116. * {@inheritdoc}
  117. */
  118. protected function _getPortableTriggerDefinition($trigger)
  119. {
  120. return $trigger['trigger_name'];
  121. }
  122. /**
  123. * {@inheritdoc}
  124. */
  125. protected function _getPortableViewDefinition($view)
  126. {
  127. return new View($view['schemaname'].'.'.$view['viewname'], $view['definition']);
  128. }
  129. /**
  130. * {@inheritdoc}
  131. */
  132. protected function _getPortableUserDefinition($user)
  133. {
  134. return array(
  135. 'user' => $user['usename'],
  136. 'password' => $user['passwd']
  137. );
  138. }
  139. /**
  140. * {@inheritdoc}
  141. */
  142. protected function _getPortableTableDefinition($table)
  143. {
  144. $schemas = $this->getExistingSchemaSearchPaths();
  145. $firstSchema = array_shift($schemas);
  146. if ($table['schema_name'] == $firstSchema) {
  147. return $table['table_name'];
  148. } else {
  149. return $table['schema_name'] . "." . $table['table_name'];
  150. }
  151. }
  152. /**
  153. * {@inheritdoc}
  154. *
  155. * @license New BSD License
  156. * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
  157. */
  158. protected function _getPortableTableIndexesList($tableIndexes, $tableName=null)
  159. {
  160. $buffer = array();
  161. foreach ($tableIndexes as $row) {
  162. $colNumbers = explode(' ', $row['indkey']);
  163. $colNumbersSql = 'IN (' . join(' ,', $colNumbers) . ' )';
  164. $columnNameSql = "SELECT attnum, attname FROM pg_attribute
  165. WHERE attrelid={$row['indrelid']} AND attnum $colNumbersSql ORDER BY attnum ASC;";
  166. $stmt = $this->_conn->executeQuery($columnNameSql);
  167. $indexColumns = $stmt->fetchAll();
  168. // required for getting the order of the columns right.
  169. foreach ($colNumbers as $colNum) {
  170. foreach ($indexColumns as $colRow) {
  171. if ($colNum == $colRow['attnum']) {
  172. $buffer[] = array(
  173. 'key_name' => $row['relname'],
  174. 'column_name' => trim($colRow['attname']),
  175. 'non_unique' => !$row['indisunique'],
  176. 'primary' => $row['indisprimary'],
  177. 'where' => $row['where'],
  178. );
  179. }
  180. }
  181. }
  182. }
  183. return parent::_getPortableTableIndexesList($buffer, $tableName);
  184. }
  185. /**
  186. * {@inheritdoc}
  187. */
  188. protected function _getPortableDatabaseDefinition($database)
  189. {
  190. return $database['datname'];
  191. }
  192. /**
  193. * {@inheritdoc}
  194. */
  195. protected function _getPortableSequencesList($sequences)
  196. {
  197. $sequenceDefinitions = array();
  198. foreach ($sequences as $sequence) {
  199. if ($sequence['schemaname'] != 'public') {
  200. $sequenceName = $sequence['schemaname'] . "." . $sequence['relname'];
  201. } else {
  202. $sequenceName = $sequence['relname'];
  203. }
  204. $sequenceDefinitions[$sequenceName] = $sequence;
  205. }
  206. $list = array();
  207. foreach ($this->filterAssetNames(array_keys($sequenceDefinitions)) as $sequenceName) {
  208. $list[] = $this->_getPortableSequenceDefinition($sequenceDefinitions[$sequenceName]);
  209. }
  210. return $list;
  211. }
  212. /**
  213. * {@inheritdoc}
  214. */
  215. protected function getPortableNamespaceDefinition(array $namespace)
  216. {
  217. return $namespace['nspname'];
  218. }
  219. /**
  220. * {@inheritdoc}
  221. */
  222. protected function _getPortableSequenceDefinition($sequence)
  223. {
  224. if ($sequence['schemaname'] != 'public') {
  225. $sequenceName = $sequence['schemaname'] . "." . $sequence['relname'];
  226. } else {
  227. $sequenceName = $sequence['relname'];
  228. }
  229. $data = $this->_conn->fetchAll('SELECT min_value, increment_by FROM ' . $this->_platform->quoteIdentifier($sequenceName));
  230. return new Sequence($sequenceName, $data[0]['increment_by'], $data[0]['min_value']);
  231. }
  232. /**
  233. * {@inheritdoc}
  234. */
  235. protected function _getPortableTableColumnDefinition($tableColumn)
  236. {
  237. $tableColumn = array_change_key_case($tableColumn, CASE_LOWER);
  238. if (strtolower($tableColumn['type']) === 'varchar' || strtolower($tableColumn['type']) === 'bpchar') {
  239. // get length from varchar definition
  240. $length = preg_replace('~.*\(([0-9]*)\).*~', '$1', $tableColumn['complete_type']);
  241. $tableColumn['length'] = $length;
  242. }
  243. $matches = array();
  244. $autoincrement = false;
  245. if (preg_match("/^nextval\('(.*)'(::.*)?\)$/", $tableColumn['default'], $matches)) {
  246. $tableColumn['sequence'] = $matches[1];
  247. $tableColumn['default'] = null;
  248. $autoincrement = true;
  249. }
  250. if (preg_match("/^'(.*)'::.*$/", $tableColumn['default'], $matches)) {
  251. $tableColumn['default'] = $matches[1];
  252. }
  253. if (stripos($tableColumn['default'], 'NULL') === 0) {
  254. $tableColumn['default'] = null;
  255. }
  256. $length = (isset($tableColumn['length'])) ? $tableColumn['length'] : null;
  257. if ($length == '-1' && isset($tableColumn['atttypmod'])) {
  258. $length = $tableColumn['atttypmod'] - 4;
  259. }
  260. if ((int) $length <= 0) {
  261. $length = null;
  262. }
  263. $fixed = null;
  264. if (!isset($tableColumn['name'])) {
  265. $tableColumn['name'] = '';
  266. }
  267. $precision = null;
  268. $scale = null;
  269. $dbType = strtolower($tableColumn['type']);
  270. if (strlen($tableColumn['domain_type']) && !$this->_platform->hasDoctrineTypeMappingFor($tableColumn['type'])) {
  271. $dbType = strtolower($tableColumn['domain_type']);
  272. $tableColumn['complete_type'] = $tableColumn['domain_complete_type'];
  273. }
  274. $type = $this->_platform->getDoctrineTypeMapping($dbType);
  275. $type = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
  276. $tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);
  277. switch ($dbType) {
  278. case 'smallint':
  279. case 'int2':
  280. $length = null;
  281. break;
  282. case 'int':
  283. case 'int4':
  284. case 'integer':
  285. $length = null;
  286. break;
  287. case 'bigint':
  288. case 'int8':
  289. $length = null;
  290. break;
  291. case 'bool':
  292. case 'boolean':
  293. if ($tableColumn['default'] === 'true') {
  294. $tableColumn['default'] = true;
  295. }
  296. if ($tableColumn['default'] === 'false') {
  297. $tableColumn['default'] = false;
  298. }
  299. $length = null;
  300. break;
  301. case 'text':
  302. $fixed = false;
  303. break;
  304. case 'varchar':
  305. case 'interval':
  306. case '_varchar':
  307. $fixed = false;
  308. break;
  309. case 'char':
  310. case 'bpchar':
  311. $fixed = true;
  312. break;
  313. case 'float':
  314. case 'float4':
  315. case 'float8':
  316. case 'double':
  317. case 'double precision':
  318. case 'real':
  319. case 'decimal':
  320. case 'money':
  321. case 'numeric':
  322. if (preg_match('([A-Za-z]+\(([0-9]+)\,([0-9]+)\))', $tableColumn['complete_type'], $match)) {
  323. $precision = $match[1];
  324. $scale = $match[2];
  325. $length = null;
  326. }
  327. break;
  328. case 'year':
  329. $length = null;
  330. break;
  331. }
  332. if ($tableColumn['default'] && preg_match("('([^']+)'::)", $tableColumn['default'], $match)) {
  333. $tableColumn['default'] = $match[1];
  334. }
  335. $options = array(
  336. 'length' => $length,
  337. 'notnull' => (bool) $tableColumn['isnotnull'],
  338. 'default' => $tableColumn['default'],
  339. 'primary' => (bool) ($tableColumn['pri'] == 't'),
  340. 'precision' => $precision,
  341. 'scale' => $scale,
  342. 'fixed' => $fixed,
  343. 'unsigned' => false,
  344. 'autoincrement' => $autoincrement,
  345. 'comment' => isset($tableColumn['comment']) && $tableColumn['comment'] !== ''
  346. ? $tableColumn['comment']
  347. : null,
  348. );
  349. $column = new Column($tableColumn['field'], Type::getType($type), $options);
  350. if (isset($tableColumn['collation']) && !empty($tableColumn['collation'])) {
  351. $column->setPlatformOption('collation', $tableColumn['collation']);
  352. }
  353. return $column;
  354. }
  355. }