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.
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>.
20 namespace Doctrine\DBAL\Platforms;
22 use Doctrine\DBAL\Schema\TableDiff,
23 Doctrine\DBAL\Schema\Table;
29 * @author Roman Borschel <roman@code-factory.org>
30 * @author Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
31 * @author Benjamin Eberlei <kontakt@beberlei.de>
32 * @todo Rename: PostgreSQLPlatform
34 class PostgreSqlPlatform extends AbstractPlatform
39 public function getSubstringExpression($value, $from, $length = null)
41 if ($length === null) {
42 return 'SUBSTR(' . $value . ', ' . $from . ')';
45 return 'SUBSTR(' . $value . ', ' . $from . ', ' . $length . ')';
51 public function getNowExpression()
53 return 'LOCALTIMESTAMP(0)';
59 public function getRegexpExpression()
67 public function getLocateExpression($str, $substr, $startPos = false)
69 if ($startPos !== false) {
70 $str = $this->getSubstringExpression($str, $startPos);
72 return 'CASE WHEN (POSITION('.$substr.' IN '.$str.') = 0) THEN 0 ELSE (POSITION('.$substr.' IN '.$str.') + '.($startPos-1).') END';
75 return 'POSITION('.$substr.' IN '.$str.')';
81 public function getDateDiffExpression($date1, $date2)
83 return '(DATE(' . $date1 . ')-DATE(' . $date2 . '))';
89 public function getDateAddDaysExpression($date, $days)
91 return "(" . $date ." + (" . $days . " || ' day')::interval)";
97 public function getDateSubDaysExpression($date, $days)
99 return "(" . $date ." - (" . $days . " || ' day')::interval)";
105 public function getDateAddMonthExpression($date, $months)
107 return "(" . $date ." + (" . $months . " || ' month')::interval)";
113 public function getDateSubMonthExpression($date, $months)
115 return "(" . $date ." - (" . $months . " || ' month')::interval)";
121 public function supportsSequences()
129 public function supportsSchemas()
137 public function supportsIdentityColumns()
145 public function supportsCommentOnStatement()
153 public function prefersSequences()
158 public function getListDatabasesSQL()
160 return 'SELECT datname FROM pg_database';
163 public function getListSequencesSQL($database)
166 c.relname, n.nspname AS schemaname
168 pg_class c, pg_namespace n
169 WHERE relkind = 'S' AND n.oid = c.relnamespace AND
170 (n.nspname NOT LIKE 'pg_%' AND n.nspname != 'information_schema')";
173 public function getListTablesSQL()
175 return "SELECT tablename AS table_name, schemaname AS schema_name
176 FROM pg_tables WHERE schemaname NOT LIKE 'pg_%' AND schemaname != 'information_schema' AND tablename != 'geometry_columns' AND tablename != 'spatial_ref_sys'";
182 public function getListViewsSQL($database)
184 return 'SELECT viewname, definition FROM pg_views';
187 public function getListTableForeignKeysSQL($table, $database = null)
189 return "SELECT r.conname, pg_catalog.pg_get_constraintdef(r.oid, true) as condef
190 FROM pg_catalog.pg_constraint r
194 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n
195 WHERE " .$this->getTableWhereClause($table) ." AND n.oid = c.relnamespace
197 AND r.contype = 'f'";
200 public function getCreateViewSQL($name, $sql)
202 return 'CREATE VIEW ' . $name . ' AS ' . $sql;
205 public function getDropViewSQL($name)
207 return 'DROP VIEW '. $name;
210 public function getListTableConstraintsSQL($table)
218 FROM pg_index, pg_class
219 WHERE pg_class.relname = '$table'
220 AND pg_class.oid = pg_index.indrelid
221 AND (indisunique = 't' OR indisprimary = 't')
228 * @license New BSD License
229 * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
231 public function getListTableIndexesSQL($table, $currentDatabase = null)
233 return "SELECT relname, pg_index.indisunique, pg_index.indisprimary,
234 pg_index.indkey, pg_index.indrelid
235 FROM pg_class, pg_index
238 FROM pg_index si, pg_class sc, pg_namespace sn
239 WHERE " . $this->getTableWhereClause($table, 'sc', 'sn')." AND sc.oid=si.indrelid AND sc.relnamespace = sn.oid
240 ) AND pg_index.indexrelid = oid";
244 * @param string $table
245 * @param string $classAlias
246 * @param string $namespaceAlias
250 private function getTableWhereClause($table, $classAlias = 'c', $namespaceAlias = 'n')
252 $whereClause = $namespaceAlias.".nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast') AND ";
253 if (strpos($table, ".") !== false) {
254 list($schema, $table) = explode(".", $table);
255 $schema = "'" . $schema . "'";
257 $schema = "ANY(string_to_array((select setting from pg_catalog.pg_settings where name = 'search_path'),','))";
259 $whereClause .= "$classAlias.relname = '" . $table . "' AND $namespaceAlias.nspname = $schema";
264 public function getListTableColumnsSQL($table, $database = null)
270 format_type(a.atttypid, a.atttypmod) AS complete_type,
271 (SELECT t1.typname FROM pg_catalog.pg_type t1 WHERE t1.oid = t.typbasetype) AS domain_type,
272 (SELECT format_type(t2.typbasetype, t2.typtypmod) FROM pg_catalog.pg_type t2
273 WHERE t2.typtype = 'd' AND t2.typname = format_type(a.atttypid, a.atttypmod)) AS domain_complete_type,
274 a.attnotnull AS isnotnull,
277 WHERE c.oid = pg_index.indrelid
278 AND pg_index.indkey[0] = a.attnum
279 AND pg_index.indisprimary = 't'
281 (SELECT pg_attrdef.adsrc
283 WHERE c.oid = pg_attrdef.adrelid
284 AND pg_attrdef.adnum=a.attnum
286 (SELECT pg_description.description
287 FROM pg_description WHERE pg_description.objoid = c.oid AND a.attnum = pg_description.objsubid
289 FROM pg_attribute a, pg_class c, pg_type t, pg_namespace n
290 WHERE ".$this->getTableWhereClause($table, 'c', 'n') ."
292 AND a.attrelid = c.oid
293 AND a.atttypid = t.oid
294 AND n.oid = c.relnamespace
301 public function getCreateDatabaseSQL($name)
303 return 'CREATE DATABASE ' . $name;
309 public function getAdvancedForeignKeyOptionsSQL(\Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey)
313 if ($foreignKey->hasOption('match')) {
314 $query .= ' MATCH ' . $foreignKey->getOption('match');
317 $query .= parent::getAdvancedForeignKeyOptionsSQL($foreignKey);
319 if ($foreignKey->hasOption('deferrable') && $foreignKey->getOption('deferrable') !== false) {
320 $query .= ' DEFERRABLE';
322 $query .= ' NOT DEFERRABLE';
325 if ($foreignKey->hasOption('feferred') && $foreignKey->getOption('feferred') !== false) {
326 $query .= ' INITIALLY DEFERRED';
328 $query .= ' INITIALLY IMMEDIATE';
337 public function getAlterTableSQL(TableDiff $diff)
340 $commentsSQL = array();
341 $columnSql = array();
343 foreach ($diff->addedColumns as $column) {
344 if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
348 $query = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
349 $sql[] = 'ALTER TABLE ' . $diff->name . ' ' . $query;
350 if ($comment = $this->getColumnComment($column)) {
351 $commentsSQL[] = $this->getCommentOnColumnSQL($diff->name, $column->getName(), $comment);
355 foreach ($diff->removedColumns as $column) {
356 if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
360 $query = 'DROP ' . $column->getQuotedName($this);
361 $sql[] = 'ALTER TABLE ' . $diff->name . ' ' . $query;
364 foreach ($diff->changedColumns as $columnDiff) {
365 /** @var $columnDiff \Doctrine\DBAL\Schema\ColumnDiff */
366 if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
370 $oldColumnName = $columnDiff->oldColumnName;
371 $column = $columnDiff->column;
373 if ($columnDiff->hasChanged('type')) {
374 $type = $column->getType();
376 // here was a server version check before, but DBAL API does not support this anymore.
377 $query = 'ALTER ' . $oldColumnName . ' TYPE ' . $type->getSqlDeclaration($column->toArray(), $this);
378 $sql[] = 'ALTER TABLE ' . $diff->name . ' ' . $query;
381 if ($columnDiff->hasChanged('default')) {
382 $query = 'ALTER ' . $oldColumnName . ' SET ' . $this->getDefaultValueDeclarationSQL($column->toArray());
383 $sql[] = 'ALTER TABLE ' . $diff->name . ' ' . $query;
386 if ($columnDiff->hasChanged('notnull')) {
387 $query = 'ALTER ' . $oldColumnName . ' ' . ($column->getNotNull() ? 'SET' : 'DROP') . ' NOT NULL';
388 $sql[] = 'ALTER TABLE ' . $diff->name . ' ' . $query;
391 if ($columnDiff->hasChanged('autoincrement')) {
392 if ($column->getAutoincrement()) {
394 $seqName = $diff->name . '_' . $oldColumnName . '_seq';
396 $sql[] = "CREATE SEQUENCE " . $seqName;
397 $sql[] = "SELECT setval('" . $seqName . "', (SELECT MAX(" . $oldColumnName . ") FROM " . $diff->name . "))";
398 $query = "ALTER " . $oldColumnName . " SET DEFAULT nextval('" . $seqName . "')";
399 $sql[] = "ALTER TABLE " . $diff->name . " " . $query;
401 // Drop autoincrement, but do NOT drop the sequence. It might be re-used by other tables or have
402 $query = "ALTER " . $oldColumnName . " " . "DROP DEFAULT";
403 $sql[] = "ALTER TABLE " . $diff->name . " " . $query;
407 if ($columnDiff->hasChanged('comment') && $comment = $this->getColumnComment($column)) {
408 $commentsSQL[] = $this->getCommentOnColumnSQL($diff->name, $column->getName(), $comment);
412 foreach ($diff->renamedColumns as $oldColumnName => $column) {
413 if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
417 $sql[] = 'ALTER TABLE ' . $diff->name . ' RENAME COLUMN ' . $oldColumnName . ' TO ' . $column->getQuotedName($this);
422 if ( ! $this->onSchemaAlterTable($diff, $tableSql)) {
423 if ($diff->newName !== false) {
424 $sql[] = 'ALTER TABLE ' . $diff->name . ' RENAME TO ' . $diff->newName;
427 $sql = array_merge($sql, $this->_getAlterTableIndexForeignKeySQL($diff), $commentsSQL);
430 return array_merge($sql, $tableSql, $columnSql);
436 public function getCreateSequenceSQL(\Doctrine\DBAL\Schema\Sequence $sequence)
438 return 'CREATE SEQUENCE ' . $sequence->getQuotedName($this) .
439 ' INCREMENT BY ' . $sequence->getAllocationSize() .
440 ' MINVALUE ' . $sequence->getInitialValue() .
441 ' START ' . $sequence->getInitialValue();
447 public function getAlterSequenceSQL(\Doctrine\DBAL\Schema\Sequence $sequence)
449 return 'ALTER SEQUENCE ' . $sequence->getQuotedName($this) .
450 ' INCREMENT BY ' . $sequence->getAllocationSize();
456 public function getDropSequenceSQL($sequence)
458 if ($sequence instanceof \Doctrine\DBAL\Schema\Sequence) {
459 $sequence = $sequence->getQuotedName($this);
461 return 'DROP SEQUENCE ' . $sequence;
467 public function getDropForeignKeySQL($foreignKey, $table)
469 return $this->getDropConstraintSQL($foreignKey, $table);
475 protected function _getCreateTableSQL($tableName, array $columns, array $options = array())
477 $queryFields = $this->getColumnDeclarationListSQL($columns);
479 if (isset($options['primary']) && ! empty($options['primary'])) {
480 $keyColumns = array_unique(array_values($options['primary']));
481 $queryFields .= ', PRIMARY KEY(' . implode(', ', $keyColumns) . ')';
484 $query = 'CREATE TABLE ' . $tableName . ' (' . $queryFields . ')';
488 if (isset($options['indexes']) && ! empty($options['indexes'])) {
489 foreach ($options['indexes'] as $index) {
490 $sql[] = $this->getCreateIndexSQL($index, $tableName);
494 if (isset($options['foreignKeys'])) {
495 foreach ((array) $options['foreignKeys'] as $definition) {
496 $sql[] = $this->getCreateForeignKeySQL($definition, $tableName);
506 * Postgres wants boolean values converted to the strings 'true'/'false'.
508 public function convertBooleans($item)
510 if (is_array($item)) {
511 foreach ($item as $key => $value) {
512 if (is_bool($value) || is_numeric($item)) {
513 $item[$key] = ($value) ? 'true' : 'false';
517 if (is_bool($item) || is_numeric($item)) {
518 $item = ($item) ? 'true' : 'false';
525 public function getSequenceNextValSQL($sequenceName)
527 return "SELECT NEXTVAL('" . $sequenceName . "')";
533 public function getSetTransactionIsolationSQL($level)
535 return 'SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL '
536 . $this->_getTransactionIsolationLevelSQL($level);
542 public function getBooleanTypeDeclarationSQL(array $field)
550 public function getIntegerTypeDeclarationSQL(array $field)
552 if ( ! empty($field['autoincrement'])) {
562 public function getBigIntTypeDeclarationSQL(array $field)
564 if ( ! empty($field['autoincrement'])) {
573 public function getSmallIntTypeDeclarationSQL(array $field)
581 public function getGuidTypeDeclarationSQL(array $field)
589 public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
591 return 'TIMESTAMP(0) WITHOUT TIME ZONE';
597 public function getDateTimeTzTypeDeclarationSQL(array $fieldDeclaration)
599 return 'TIMESTAMP(0) WITH TIME ZONE';
605 public function getDateTypeDeclarationSQL(array $fieldDeclaration)
613 public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
615 return 'TIME(0) WITHOUT TIME ZONE';
621 protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
629 protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
631 return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)')
632 : ($length ? 'VARCHAR(' . $length . ')' : 'VARCHAR(255)');
638 public function getClobTypeDeclarationSQL(array $field)
646 public function getName()
654 * PostgreSQL returns all column names in SQL result sets in lowercase.
656 public function getSQLResultCasing($column)
658 return strtolower($column);
664 public function getDateTimeTzFormatString()
666 return 'Y-m-d H:i:sO';
672 public function getEmptyIdentityInsertSQL($quotedTableName, $quotedIdentifierColumnName)
674 return 'INSERT INTO ' . $quotedTableName . ' (' . $quotedIdentifierColumnName . ') VALUES (DEFAULT)';
680 public function getTruncateTableSQL($tableName, $cascade = false)
682 return 'TRUNCATE '.$tableName.' '.(($cascade)?'CASCADE':'');
688 public function getReadLockSQL()
696 protected function initializeDoctrineTypeMappings()
698 $this->doctrineTypeMapping = array(
699 'smallint' => 'smallint',
700 'int2' => 'smallint',
701 'serial' => 'integer',
702 'serial4' => 'integer',
705 'integer' => 'integer',
706 'bigserial' => 'bigint',
707 'serial8' => 'bigint',
708 'bigint' => 'bigint',
711 'boolean' => 'boolean',
713 'varchar' => 'string',
714 'interval' => 'string',
715 '_varchar' => 'string',
717 'bpchar' => 'string',
719 'datetime' => 'datetime',
720 'timestamp' => 'datetime',
721 'timestamptz' => 'datetimetz',
728 'double precision' => 'float',
730 'decimal' => 'decimal',
731 'money' => 'decimal',
732 'numeric' => 'decimal',
742 public function getVarcharMaxLength()
750 protected function getReservedKeywordsClass()
752 return 'Doctrine\DBAL\Platforms\Keywords\PostgreSQLKeywords';
758 public function getBlobTypeDeclarationSQL(array $field)