DB2Platform.php 17 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
 * <http://www.doctrine-project.org>.
*/

namespace Doctrine\DBAL\Platforms;

22 23 24 25
use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\Schema\Index;
use Doctrine\DBAL\Schema\TableDiff;

26
class DB2Platform extends AbstractPlatform
27
{
28 29 30 31 32 33 34 35
    /**
     * Gets the SQL Snippet used to declare a BLOB column type.
     */
    public function getBlobTypeDeclarationSQL(array $field)
    {
        throw DBALException::notSupported(__METHOD__);
    }

36 37 38 39 40 41 42 43 44 45 46 47
    public function initializeDoctrineTypeMappings()
    {
        $this->doctrineTypeMapping = array(
            'smallint'      => 'smallint',
            'bigint'        => 'bigint',
            'integer'       => 'integer',
            'time'          => 'time',
            'date'          => 'date',
            'varchar'       => 'string',
            'character'     => 'string',
            'clob'          => 'text',
            'decimal'       => 'decimal',
48 49
            'double'        => 'float',
            'real'          => 'float',
50 51 52 53
            'timestamp'     => 'datetime',
        );
    }

54 55 56 57 58
    /**
     * Gets the SQL snippet used to declare a VARCHAR column type.
     *
     * @param array $field
     */
59
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
    {
        return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)')
                : ($length ? 'VARCHAR(' . $length . ')' : 'VARCHAR(255)');
    }

    /**
     * Gets the SQL snippet used to declare a CLOB column type.
     *
     * @param array $field
     */
    public function getClobTypeDeclarationSQL(array $field)
    {
        // todo clob(n) with $field['length'];
        return 'CLOB(1M)';
    }

    /**
     * Gets the name of the platform.
     *
     * @return string
     */
    public function getName()
    {
        return 'db2';
    }


    /**
     * Gets the SQL snippet that declares a boolean column.
     *
     * @param array $columnDef
     * @return string
     */
    public function getBooleanTypeDeclarationSQL(array $columnDef)
    {
        return 'SMALLINT';
    }

    /**
     * Gets the SQL snippet that declares a 4 byte integer column.
     *
     * @param array $columnDef
     * @return string
     */
    public function getIntegerTypeDeclarationSQL(array $columnDef)
    {
106
        return 'INTEGER' . $this->_getCommonIntegerTypeDeclarationSQL($columnDef);
107 108 109 110 111 112 113 114 115 116
    }

    /**
     * Gets the SQL snippet that declares an 8 byte integer column.
     *
     * @param array $columnDef
     * @return string
     */
    public function getBigIntTypeDeclarationSQL(array $columnDef)
    {
117
        return 'BIGINT' . $this->_getCommonIntegerTypeDeclarationSQL($columnDef);
118 119 120 121 122 123 124 125 126 127
    }

    /**
     * Gets the SQL snippet that declares a 2 byte integer column.
     *
     * @param array $columnDef
     * @return string
     */
    public function getSmallIntTypeDeclarationSQL(array $columnDef)
    {
128
        return 'SMALLINT' . $this->_getCommonIntegerTypeDeclarationSQL($columnDef);
129 130 131 132 133 134 135 136 137 138
    }

    /**
     * Gets the SQL snippet that declares common properties of an integer column.
     *
     * @param array $columnDef
     * @return string
     */
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
    {
139 140 141 142 143
        $autoinc = '';
        if ( ! empty($columnDef['autoincrement'])) {
            $autoinc = ' GENERATED BY DEFAULT AS IDENTITY';
        }
        return $autoinc;
144 145
    }

146 147 148 149 150 151 152 153 154
    /**
     * Obtain DBMS specific SQL to be used to create datetime fields in
     * statements like CREATE TABLE
     *
     * @param array $fieldDeclaration
     * @return string
     */
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
    {
155 156 157 158
        if (isset($fieldDeclaration['version']) && $fieldDeclaration['version'] == true) {
            return "TIMESTAMP(0) WITH DEFAULT";
        }

159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
        return 'TIMESTAMP(0)';
    }

    /**
     * Obtain DBMS specific SQL to be used to create date fields in statements
     * like CREATE TABLE.
     *
     * @param array $fieldDeclaration
     * @return string
     */
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
    {
        return 'DATE';
    }

    /**
     * Obtain DBMS specific SQL to be used to create time fields in statements
     * like CREATE TABLE.
     *
     * @param array $fieldDeclaration
     * @return string
     */
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
    {
        return 'TIME';
    }

186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
    public function getListDatabasesSQL()
    {
        throw DBALException::notSupported(__METHOD__);
    }

    public function getListSequencesSQL($database)
    {
        throw DBALException::notSupported(__METHOD__);
    }

    public function getListTableConstraintsSQL($table)
    {
        throw DBALException::notSupported(__METHOD__);
    }

201 202 203 204 205 206 207
    /**
     * This code fragment is originally from the Zend_Db_Adapter_Db2 class.
     *
     * @license New BSD License
     * @param  string $table
     * @return string
     */
208
    public function getListTableColumnsSQL($table, $database = null)
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
    {
        return "SELECT DISTINCT c.tabschema, c.tabname, c.colname, c.colno,
                c.typename, c.default, c.nulls, c.length, c.scale,
                c.identity, tc.type AS tabconsttype, k.colseq
                FROM syscat.columns c
                LEFT JOIN (syscat.keycoluse k JOIN syscat.tabconst tc
                ON (k.tabschema = tc.tabschema
                    AND k.tabname = tc.tabname
                    AND tc.type = 'P'))
                ON (c.tabschema = k.tabschema
                    AND c.tabname = k.tabname
                    AND c.colname = k.colname)
                WHERE UPPER(c.tabname) = UPPER('" . $table . "') ORDER BY c.colno";
    }

    public function getListTablesSQL()
    {
226
        return "SELECT NAME FROM SYSIBM.SYSTABLES WHERE TYPE = 'T'";
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
    }

    public function getListUsersSQL()
    {
        throw DBALException::notSupported(__METHOD__);
    }

    /**
     * Get the SQL to list all views of a database or user.
     *
     * @param string $database
     * @return string
     */
    public function getListViewsSQL($database)
    {
        return "SELECT NAME, TEXT FROM SYSIBM.SYSVIEWS";
    }

245
    public function getListTableIndexesSQL($table, $currentDatabase = null)
246
    {
247
        return "SELECT NAME, COLNAMES, UNIQUERULE FROM SYSIBM.SYSINDEXES WHERE TBNAME = UPPER('" . $table . "')";
248 249 250 251
    }

    public function getListTableForeignKeysSQL($table)
    {
252 253
        return "SELECT TBNAME, RELNAME, REFTBNAME, DELETERULE, UPDATERULE, FKCOLNAMES, PKCOLNAMES ".
               "FROM SYSIBM.SYSRELS WHERE TBNAME = UPPER('".$table."')";
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
    }

    public function getCreateViewSQL($name, $sql)
    {
        return "CREATE VIEW ".$name." AS ".$sql;
    }

    public function getDropViewSQL($name)
    {
        return "DROP VIEW ".$name;
    }

    public function getDropSequenceSQL($sequence)
    {
        throw DBALException::notSupported(__METHOD__);
    }

    public function getSequenceNextValSQL($sequenceName)
    {
        throw DBALException::notSupported(__METHOD__);
    }

    public function getCreateDatabaseSQL($database)
    {
        return "CREATE DATABASE ".$database;
    }

    public function getDropDatabaseSQL($database)
    {
        return "DROP DATABASE ".$database.";";
    }

    public function supportsCreateDropDatabase()
    {
        return false;
    }
290

291 292 293 294 295 296 297 298 299 300
    /**
     * Whether the platform supports releasing savepoints.
     *
     * @return boolean
     */
    public function supportsReleaseSavepoints()
    {
        return false;
    }

301 302 303 304 305 306 307
    /**
     * Gets the SQL specific for the platform to get the current date.
     *
     * @return string
     */
    public function getCurrentDateSQL()
    {
308
        return 'VALUES CURRENT DATE';
309 310 311 312 313 314 315 316 317
    }

    /**
     * Gets the SQL specific for the platform to get the current time.
     *
     * @return string
     */
    public function getCurrentTimeSQL()
    {
318
        return 'VALUES CURRENT TIME';
319 320 321 322 323 324 325
    }

    /**
     * Gets the SQL specific for the platform to get the current timestamp
     *
     * @return string
     */
326 327

    public function getCurrentTimestampSQL()
328
    {
329 330
        return "VALUES CURRENT TIMESTAMP";
    }
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357

    /**
     * Obtain DBMS specific SQL code portion needed to set an index
     * declaration to be used in statements like CREATE TABLE.
     *
     * @param string $name          name of the index
     * @param Index $index          index definition
     * @return string               DBMS specific SQL code portion needed to set an index
     */
    public function getIndexDeclarationSQL($name, Index $index)
    {
        return $this->getUniqueConstraintDeclarationSQL($name, $index);
    }

    /**
     * @param string $tableName
     * @param array $columns
     * @param array $options
     * @return array
     */
    protected function _getCreateTableSQL($tableName, array $columns, array $options = array())
    {
        $indexes = array();
        if (isset($options['indexes'])) {
            $indexes = $options['indexes'];
        }
        $options['indexes'] = array();
358

359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
        $sqls = parent::_getCreateTableSQL($tableName, $columns, $options);

        foreach ($indexes as $index => $definition) {
            $sqls[] = $this->getCreateIndexSQL($definition, $tableName);
        }
        return $sqls;
    }

    /**
     * Gets the SQL to alter an existing table.
     *
     * @param TableDiff $diff
     * @return array
     */
    public function getAlterTableSQL(TableDiff $diff)
    {
        $sql = array();
376
        $columnSql = array();
377 378 379

        $queryParts = array();
        foreach ($diff->addedColumns AS $fieldName => $column) {
380 381
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
                continue;
382 383
            }

384
            $queryParts[] = 'ADD COLUMN ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
385 386 387
        }

        foreach ($diff->removedColumns AS $column) {
388 389
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
                continue;
390 391
            }

392
            $queryParts[] =  'DROP COLUMN ' . $column->getQuotedName($this);
393 394 395
        }

        foreach ($diff->changedColumns AS $columnDiff) {
396 397
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
                continue;
398 399
            }

400 401 402
            /* @var $columnDiff Doctrine\DBAL\Schema\ColumnDiff */
            $column = $columnDiff->column;
            $queryParts[] =  'ALTER ' . ($columnDiff->oldColumnName) . ' '
403
                    . $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
404 405 406
        }

        foreach ($diff->renamedColumns AS $oldColumnName => $column) {
407 408
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
                continue;
409 410
            }

411
            $queryParts[] =  'RENAME ' . $oldColumnName . ' TO ' . $column->getQuotedName($this);
412 413
        }

414 415 416 417 418 419
        $tableSql = array();

        if (!$this->onSchemaAlterTable($diff, $tableSql)) {
            if (count($queryParts) > 0) {
                $sql[] = 'ALTER TABLE ' . $diff->name . ' ' . implode(" ", $queryParts);
            }
420

421
            $sql = array_merge($sql, $this->_getAlterTableIndexForeignKeySQL($diff));
422

423 424 425
            if ($diff->newName !== false) {
                $sql[] =  'RENAME TABLE TO ' . $diff->newName;
            }
426 427
        }

428
        return array_merge($sql, $tableSql, $columnSql);
429 430 431 432 433 434 435
    }

    public function getDefaultValueDeclarationSQL($field)
    {
        if (isset($field['notnull']) && $field['notnull'] && !isset($field['default'])) {
            if (in_array((string)$field['type'], array("Integer", "BigInteger", "SmallInteger"))) {
                $field['default'] = 0;
436 437 438 439 440 441
            } else if((string)$field['type'] == "DateTime") {
                $field['default'] = "00-00-00 00:00:00";
            } else if ((string)$field['type'] == "Date") {
                $field['default'] = "00-00-00";
            } else if((string)$field['type'] == "Time") {
                $field['default'] = "00:00:00";
442 443 444 445 446
            } else {
                $field['default'] = '';
            }
        }

447 448 449 450 451 452 453
        unset($field['default']); // @todo this needs fixing
        if (isset($field['version']) && $field['version']) {
            if ((string)$field['type'] != "DateTime") {
                $field['default'] = "1";
            }
        }

454 455 456
        return parent::getDefaultValueDeclarationSQL($field);
    }

457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
    /**
     * Get the insert sql for an empty insert statement
     *
     * @param string $tableName
     * @param string $identifierColumnName
     * @return string $sql
     */
    public function getEmptyIdentityInsertSQL($tableName, $identifierColumnName)
    {
        return 'INSERT INTO ' . $tableName . ' (' . $identifierColumnName . ') VALUES (DEFAULT)';
    }

    public function getCreateTemporaryTableSnippetSQL()
    {
        return "DECLARE GLOBAL TEMPORARY TABLE";
    }

    /**
     * DB2 automatically moves temporary tables into the SESSION. schema.
     *
     * @param  string $tableName
     * @return string
     */
    public function getTemporaryTableName($tableName)
    {
        return "SESSION." . $tableName;
    }

485
    protected function doModifyLimitQuery($query, $limit, $offset = null)
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
    {
        if ($limit === null && $offset === null) {
            return $query;
        }

        $limit = (int)$limit;
        $offset = (int)(($offset)?:0);

        // Todo OVER() needs ORDER BY data!
        $sql = 'SELECT db22.* FROM (SELECT ROW_NUMBER() OVER() AS DC_ROWNUM, db21.* '.
               'FROM (' . $query . ') db21) db22 WHERE db22.DC_ROWNUM BETWEEN ' . ($offset+1) .' AND ' . ($offset+$limit);
        return $sql;
    }

    /**
     * returns the position of the first occurrence of substring $substr in string $str
     *
     * @param string $substr    literal string to find
     * @param string $str       literal string
     * @param int    $pos       position to start at, beginning of string by default
     * @return integer
     */
    public function getLocateExpression($str, $substr, $startPos = false)
    {
        if ($startPos == false) {
            return 'LOCATE(' . $substr . ', ' . $str . ')';
        } else {
            return 'LOCATE(' . $substr . ', ' . $str . ', '.$startPos.')';
        }
    }

    /**
     * return string to call a function to get a substring inside an SQL statement
     *
     * Note: Not SQL92, but common functionality.
     *
     * SQLite only supports the 2 parameter variant of this function
     *
     * @param  string $value         an sql string literal or column name/alias
     * @param  integer $from     where to start the substring portion
     * @param  integer $len       the substring portion length
     * @return string
     */
    public function getSubstringExpression($value, $from, $len = null)
    {
        if ($len === null)
            return 'SUBSTR(' . $value . ', ' . $from . ')';
        else {
            return 'SUBSTR(' . $value . ', ' . $from . ', ' . $len . ')';
        }
    }

538 539 540 541 542 543 544 545 546
    public function supportsIdentityColumns()
    {
        return true;
    }

    public function prefersIdentityColumns()
    {
        return true;
    }
547 548 549 550 551 552 553 554 555 556 557 558 559

    /**
     * Gets the character casing of a column in an SQL result set of this platform.
     *
     * DB2 returns all column names in SQL result sets in uppercase.
     *
     * @param string $column The column name for which to get the correct character casing.
     * @return string The column name in the character casing used in SQL result sets.
     */
    public function getSQLResultCasing($column)
    {
        return strtoupper($column);
    }
560 561 562 563 564

    public function getForUpdateSQL()
    {
        return ' WITH RR USE AND KEEP UPDATE LOCKS';
    }
565 566 567 568 569

    public function getDummySelectSQL()
    {
        return 'SELECT 1 FROM sysibm.sysdummy1';
    }
570 571 572 573 574 575 576 577 578 579 580 581

    /**
     * DB2 supports savepoints, but they work semantically different than on other vendor platforms.
     *
     * TODO: We have to investigate how to get DB2 up and running with savepoints.
     *
     * @return bool
     */
    public function supportsSavepoints()
    {
        return false;
    }
582

583 584 585 586
    protected function getReservedKeywordsClass()
    {
        return 'Doctrine\DBAL\Platforms\Keywords\DB2Keywords';
    }
587
}