PostgreSqlSchemaManager.php 12 KB

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