4 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
5 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
6 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
12 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
13 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
14 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
16 * This software consists of voluntary contributions made by many individuals
17 * and is licensed under the MIT license. For more information, see
18 * <http://www.doctrine-project.org>.
21 namespace Doctrine\DBAL\Schema;
24 * PostgreSQL Schema Manager
26 * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
27 * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
28 * @author Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
29 * @author Benjamin Eberlei <kontakt@beberlei.de>
32 class PostgreSqlSchemaManager extends AbstractSchemaManager
37 private $existingSchemaPaths;
40 * Get all the existing schema names.
44 public function getSchemaNames()
46 $rows = $this->_conn->fetchAll("SELECT nspname as schema_name FROM pg_namespace WHERE nspname !~ '^pg_.*' and nspname != 'information_schema'");
47 return array_map(function($v) { return $v['schema_name']; }, $rows);
51 * Return an array of schema search paths
53 * This is a PostgreSQL only function.
57 public function getSchemaSearchPaths()
59 $params = $this->_conn->getParams();
60 $schema = explode(",", $this->_conn->fetchColumn('SHOW search_path'));
61 if (isset($params['user'])) {
62 $schema = str_replace('"$user"', $params['user'], $schema);
68 * Get names of all existing schemas in the current users search path.
70 * This is a PostgreSQL only function.
74 public function getExistingSchemaSearchPaths()
76 if ($this->existingSchemaPaths === null) {
77 $this->determineExistingSchemaSearchPaths();
79 return $this->existingSchemaPaths;
83 * Use this to set or reset the order of the existing schemas in the current search path of the user
85 * This is a PostgreSQL only function.
89 public function determineExistingSchemaSearchPaths()
91 $names = $this->getSchemaNames();
92 $paths = $this->getSchemaSearchPaths();
94 $this->existingSchemaPaths = array_filter($paths, function ($v) use ($names) {
95 return in_array($v, $names);
99 protected function _getPortableTableForeignKeyDefinition($tableForeignKey)
104 if (preg_match('(ON UPDATE ([a-zA-Z0-9]+( (NULL|ACTION|DEFAULT))?))', $tableForeignKey['condef'], $match)) {
105 $onUpdate = $match[1];
107 if (preg_match('(ON DELETE ([a-zA-Z0-9]+( (NULL|ACTION|DEFAULT))?))', $tableForeignKey['condef'], $match)) {
108 $onDelete = $match[1];
111 if (preg_match('/FOREIGN KEY \((.+)\) REFERENCES (.+)\((.+)\)/', $tableForeignKey['condef'], $values)) {
112 // PostgreSQL returns identifiers that are keywords with quotes, we need them later, don't get
113 // the idea to trim them here.
114 $localColumns = array_map('trim', explode(",", $values[1]));
115 $foreignColumns = array_map('trim', explode(",", $values[3]));
116 $foreignTable = $values[2];
119 return new ForeignKeyConstraint(
120 $localColumns, $foreignTable, $foreignColumns, $tableForeignKey['conname'],
121 array('onUpdate' => $onUpdate, 'onDelete' => $onDelete)
125 public function dropDatabase($database)
127 $params = $this->_conn->getParams();
128 $params["dbname"] = "postgres";
129 $tmpPlatform = $this->_platform;
130 $tmpConn = $this->_conn;
132 $this->_conn = \Doctrine\DBAL\DriverManager::getConnection($params);
133 $this->_platform = $this->_conn->getDatabasePlatform();
135 parent::dropDatabase($database);
137 $this->_platform = $tmpPlatform;
138 $this->_conn = $tmpConn;
141 public function createDatabase($database)
143 $params = $this->_conn->getParams();
144 $params["dbname"] = "postgres";
145 $tmpPlatform = $this->_platform;
146 $tmpConn = $this->_conn;
148 $this->_conn = \Doctrine\DBAL\DriverManager::getConnection($params);
149 $this->_platform = $this->_conn->getDatabasePlatform();
151 parent::createDatabase($database);
153 $this->_platform = $tmpPlatform;
154 $this->_conn = $tmpConn;
157 protected function _getPortableTriggerDefinition($trigger)
159 return $trigger['trigger_name'];
162 protected function _getPortableViewDefinition($view)
164 return new View($view['viewname'], $view['definition']);
167 protected function _getPortableUserDefinition($user)
170 'user' => $user['usename'],
171 'password' => $user['passwd']
175 protected function _getPortableTableDefinition($table)
177 $schemas = $this->getExistingSchemaSearchPaths();
178 $firstSchema = array_shift($schemas);
180 if ($table['schema_name'] == $firstSchema) {
181 return $table['table_name'];
183 return $table['schema_name'] . "." . $table['table_name'];
188 * @license New BSD License
189 * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
190 * @param array $tableIndexes
191 * @param string $tableName
194 protected function _getPortableTableIndexesList($tableIndexes, $tableName=null)
197 foreach ($tableIndexes as $row) {
198 $colNumbers = explode(' ', $row['indkey']);
199 $colNumbersSql = 'IN (' . join(' ,', $colNumbers) . ' )';
200 $columnNameSql = "SELECT attnum, attname FROM pg_attribute
201 WHERE attrelid={$row['indrelid']} AND attnum $colNumbersSql ORDER BY attnum ASC;";
203 $stmt = $this->_conn->executeQuery($columnNameSql);
204 $indexColumns = $stmt->fetchAll();
206 // required for getting the order of the columns right.
207 foreach ($colNumbers as $colNum) {
208 foreach ($indexColumns as $colRow) {
209 if ($colNum == $colRow['attnum']) {
211 'key_name' => $row['relname'],
212 'column_name' => trim($colRow['attname']),
213 'non_unique' => !$row['indisunique'],
214 'primary' => $row['indisprimary']
220 return parent::_getPortableTableIndexesList($buffer, $tableName);
223 protected function _getPortableDatabaseDefinition($database)
225 return $database['datname'];
228 protected function _getPortableSequenceDefinition($sequence)
230 if ($sequence['schemaname'] != 'public') {
231 $sequenceName = $sequence['schemaname'] . "." . $sequence['relname'];
233 $sequenceName = $sequence['relname'];
236 $data = $this->_conn->fetchAll('SELECT min_value, increment_by FROM ' . $sequenceName);
237 return new Sequence($sequenceName, $data[0]['increment_by'], $data[0]['min_value']);
240 protected function _getPortableTableColumnDefinition($tableColumn)
242 $tableColumn = array_change_key_case($tableColumn, CASE_LOWER);
244 if (strtolower($tableColumn['type']) === 'varchar') {
245 // get length from varchar definition
246 $length = preg_replace('~.*\(([0-9]*)\).*~', '$1', $tableColumn['complete_type']);
247 $tableColumn['length'] = $length;
252 $autoincrement = false;
253 if (preg_match("/^nextval\('(.*)'(::.*)?\)$/", $tableColumn['default'], $matches)) {
254 $tableColumn['sequence'] = $matches[1];
255 $tableColumn['default'] = null;
256 $autoincrement = true;
259 if (stripos($tableColumn['default'], 'NULL') === 0) {
260 $tableColumn['default'] = null;
263 $length = (isset($tableColumn['length'])) ? $tableColumn['length'] : null;
264 if ($length == '-1' && isset($tableColumn['atttypmod'])) {
265 $length = $tableColumn['atttypmod'] - 4;
267 if ((int) $length <= 0) {
272 if (!isset($tableColumn['name'])) {
273 $tableColumn['name'] = '';
279 $dbType = strtolower($tableColumn['type']);
280 if (strlen($tableColumn['domain_type']) && !$this->_platform->hasDoctrineTypeMappingFor($tableColumn['type'])) {
281 $dbType = strtolower($tableColumn['domain_type']);
282 $tableColumn['complete_type'] = $tableColumn['domain_complete_type'];
285 $type = $this->_platform->getDoctrineTypeMapping($dbType);
286 $type = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
287 $tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);
323 case 'double precision':
328 if (preg_match('([A-Za-z]+\(([0-9]+)\,([0-9]+)\))', $tableColumn['complete_type'], $match)) {
329 $precision = $match[1];
339 if ($tableColumn['default'] && preg_match("('([^']+)'::)", $tableColumn['default'], $match)) {
340 $tableColumn['default'] = $match[1];
345 'notnull' => (bool) $tableColumn['isnotnull'],
346 'default' => $tableColumn['default'],
347 'primary' => (bool) ($tableColumn['pri'] == 't'),
348 'precision' => $precision,
352 'autoincrement' => $autoincrement,
353 'comment' => $tableColumn['comment'],
356 return new Column($tableColumn['field'], \Doctrine\DBAL\Types\Type::getType($type), $options);