SqlitePlatform.php 33.5 KB
Newer Older
1
<?php
2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * 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
Benjamin Eberlei's avatar
Benjamin Eberlei committed
16
 * and is licensed under the MIT license. For more information, see
17 18
 * <http://www.doctrine-project.org>.
 */
19

20
namespace Doctrine\DBAL\Platforms;
21

22
use Doctrine\DBAL\DBALException;
23
use Doctrine\DBAL\Schema\Column;
24 25 26 27
use Doctrine\DBAL\Schema\TableDiff;
use Doctrine\DBAL\Schema\Table;
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
use Doctrine\DBAL\Schema\Index;
28
use Doctrine\DBAL\Schema\Identifier;
29
use Doctrine\DBAL\Schema\Constraint;
30

31
/**
32 33
 * The SqlitePlatform class describes the specifics and dialects of the SQLite
 * database platform.
34
 *
Benjamin Morel's avatar
Benjamin Morel committed
35
 * @since  2.0
36
 * @author Roman Borschel <roman@code-factory.org>
37
 * @author Benjamin Eberlei <kontakt@beberlei.de>
38
 * @author Martin Hasoň <martin.hason@gmail.com>
Benjamin Morel's avatar
Benjamin Morel committed
39
 * @todo   Rename: SQLitePlatform
40
 */
41
class SqlitePlatform extends AbstractPlatform
42 43
{
    /**
44
     * {@inheritDoc}
45 46 47
     */
    public function getRegexpExpression()
    {
48
        return 'REGEXP';
49 50
    }

51 52 53 54 55 56 57 58 59 60 61
    /**
     * {@inheritDoc}
     */
    public function getGuidExpression()
    {
        return "HEX(RANDOMBLOB(4)) || '-' || HEX(RANDOMBLOB(2)) || '-4' || "
            . "SUBSTR(HEX(RANDOMBLOB(2)), 2) || '-' || "
            . "SUBSTR('89AB', 1 + (ABS(RANDOM()) % 4), 1) || "
            . "SUBSTR(HEX(RANDOMBLOB(2)), 2) || '-' || HEX(RANDOMBLOB(6))";
    }

62
    /**
63
     * {@inheritDoc}
64 65 66 67 68 69 70 71 72 73 74 75 76 77
     */
    public function getNowExpression($type = 'timestamp')
    {
        switch ($type) {
            case 'time':
                return 'time(\'now\')';
            case 'date':
                return 'date(\'now\')';
            case 'timestamp':
            default:
                return 'datetime(\'now\')';
        }
    }

78
    /**
79
     * {@inheritDoc}
80 81 82 83 84
     */
    public function getTrimExpression($str, $pos = self::TRIM_UNSPECIFIED, $char = false)
    {
        $trimChar = ($char != false) ? (', ' . $char) : '';

85 86 87 88 89 90 91 92 93 94 95
        switch ($pos) {
            case self::TRIM_LEADING:
                $trimFn = 'LTRIM';
                break;

            case self::TRIM_TRAILING:
                $trimFn = 'RTRIM';
                break;

            default:
                $trimFn = 'TRIM';
96 97 98 99 100
        }

        return $trimFn . '(' . $str . $trimChar . ')';
    }

101
    /**
102
     * {@inheritDoc}
103 104 105 106 107 108 109 110
     *
     * SQLite only supports the 2 parameter variant of this function
     */
    public function getSubstringExpression($value, $position, $length = null)
    {
        if ($length !== null) {
            return 'SUBSTR(' . $value . ', ' . $position . ', ' . $length . ')';
        }
111

112 113 114
        return 'SUBSTR(' . $value . ', ' . $position . ', LENGTH(' . $value . '))';
    }

115
    /**
116
     * {@inheritDoc}
117 118 119 120 121 122
     */
    public function getLocateExpression($str, $substr, $startPos = false)
    {
        if ($startPos == false) {
            return 'LOCATE('.$str.', '.$substr.')';
        }
123 124

        return 'LOCATE('.$str.', '.$substr.', '.$startPos.')';
125 126
    }

127
    /**
128
     * {@inheritdoc}
129
     */
130
    protected function getDateArithmeticIntervalExpression($date, $operator, $interval, $unit)
131
    {
132 133 134 135 136
        switch ($unit) {
            case self::DATE_INTERVAL_UNIT_SECOND:
            case self::DATE_INTERVAL_UNIT_MINUTE:
            case self::DATE_INTERVAL_UNIT_HOUR:
                return "DATETIME(" . $date . ",'" . $operator . $interval . " " . $unit . "')";
137

138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
            default:
                switch ($unit) {
                    case self::DATE_INTERVAL_UNIT_WEEK:
                        $interval *= 7;
                        $unit = self::DATE_INTERVAL_UNIT_DAY;
                        break;

                    case self::DATE_INTERVAL_UNIT_QUARTER:
                        $interval *= 3;
                        $unit = self::DATE_INTERVAL_UNIT_MONTH;
                        break;
                }

                return "DATE(" . $date . ",'" . $operator . $interval . " " . $unit . "')";
        }
153 154
    }

155 156 157
    /**
     * {@inheritDoc}
     */
158
    public function getDateDiffExpression($date1, $date2)
159
    {
160
        return 'ROUND(JULIANDAY('.$date1 . ')-JULIANDAY('.$date2.'))';
161 162
    }

163 164 165
    /**
     * {@inheritDoc}
     */
166
    protected function _getTransactionIsolationLevelSQL($level)
romanb's avatar
romanb committed
167 168
    {
        switch ($level) {
169
            case \Doctrine\DBAL\Connection::TRANSACTION_READ_UNCOMMITTED:
romanb's avatar
romanb committed
170
                return 0;
171 172 173
            case \Doctrine\DBAL\Connection::TRANSACTION_READ_COMMITTED:
            case \Doctrine\DBAL\Connection::TRANSACTION_REPEATABLE_READ:
            case \Doctrine\DBAL\Connection::TRANSACTION_SERIALIZABLE:
romanb's avatar
romanb committed
174 175
                return 1;
            default:
176
                return parent::_getTransactionIsolationLevelSQL($level);
romanb's avatar
romanb committed
177 178
        }
    }
179

180 181 182
    /**
     * {@inheritDoc}
     */
183
    public function getSetTransactionIsolationSQL($level)
romanb's avatar
romanb committed
184
    {
185
        return 'PRAGMA read_uncommitted = ' . $this->_getTransactionIsolationLevelSQL($level);
romanb's avatar
romanb committed
186
    }
187

188
    /**
189
     * {@inheritDoc}
190
     */
191 192
    public function prefersIdentityColumns()
    {
193 194
        return true;
    }
195 196

    /**
197
     * {@inheritDoc}
198
     */
199
    public function getBooleanTypeDeclarationSQL(array $field)
200 201 202
    {
        return 'BOOLEAN';
    }
203

204
    /**
205
     * {@inheritDoc}
206
     */
207
    public function getIntegerTypeDeclarationSQL(array $field)
208
    {
209
        return 'INTEGER' . $this->_getCommonIntegerTypeDeclarationSQL($field);
210 211
    }

212
    /**
213
     * {@inheritDoc}
214
     */
215
    public function getBigIntTypeDeclarationSQL(array $field)
216
    {
217 218 219 220 221
        //  SQLite autoincrement is implicit for INTEGER PKs, but not for BIGINT fields.
        if ( ! empty($field['autoincrement'])) {
            return $this->getIntegerTypeDeclarationSQL($field);
        }

222
        return 'BIGINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
223 224
    }

225
    /**
226
     * {@inheritDoc}
227
     */
228 229
    public function getTinyIntTypeDeclarationSql(array $field)
    {
230 231 232 233 234
        //  SQLite autoincrement is implicit for INTEGER PKs, but not for TINYINT fields.
        if ( ! empty($field['autoincrement'])) {
            return $this->getIntegerTypeDeclarationSQL($field);
        }

235
        return 'TINYINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
236 237
    }

238
    /**
239
     * {@inheritDoc}
240
     */
241
    public function getSmallIntTypeDeclarationSQL(array $field)
242
    {
243 244 245 246 247
        //  SQLite autoincrement is implicit for INTEGER PKs, but not for SMALLINT fields.
        if ( ! empty($field['autoincrement'])) {
            return $this->getIntegerTypeDeclarationSQL($field);
        }

248
        return 'SMALLINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
249 250
    }

251
    /**
252
     * {@inheritDoc}
253
     */
254 255
    public function getMediumIntTypeDeclarationSql(array $field)
    {
256 257 258 259 260
        //  SQLite autoincrement is implicit for INTEGER PKs, but not for MEDIUMINT fields.
        if ( ! empty($field['autoincrement'])) {
            return $this->getIntegerTypeDeclarationSQL($field);
        }

261
        return 'MEDIUMINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
262 263
    }

264
    /**
265
     * {@inheritDoc}
266
     */
267
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
268 269 270
    {
        return 'DATETIME';
    }
271

272
    /**
273
     * {@inheritDoc}
274
     */
275
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
276 277 278
    {
        return 'DATE';
    }
279

280
    /**
281
     * {@inheritDoc}
282
     */
283
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
284 285 286 287
    {
        return 'TIME';
    }

288
    /**
289
     * {@inheritDoc}
290
     */
291
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
292
    {
293 294 295 296 297
        // sqlite autoincrement is implicit for integer PKs, but not when the field is unsigned
        if ( ! empty($columnDef['autoincrement'])) {
            return '';
        }

298
        return ! empty($columnDef['unsigned']) ? ' UNSIGNED' : '';
299 300
    }

301 302 303 304 305 306
    /**
     * {@inheritDoc}
     */
    public function getForeignKeyDeclarationSQL(ForeignKeyConstraint $foreignKey)
    {
        return parent::getForeignKeyDeclarationSQL(new ForeignKeyConstraint(
307 308 309
            $foreignKey->getQuotedLocalColumns($this),
            str_replace('.', '__', $foreignKey->getQuotedForeignTableName($this)),
            $foreignKey->getQuotedForeignColumns($this),
310 311 312 313 314
            $foreignKey->getName(),
            $foreignKey->getOptions()
        ));
    }

315
    /**
316
     * {@inheritDoc}
317
     */
318
    protected function _getCreateTableSQL($name, array $columns, array $options = array())
319
    {
320
        $name = str_replace('.', '__', $name);
321
        $queryFields = $this->getColumnDeclarationListSQL($columns);
322

323 324 325 326 327 328
        if (isset($options['uniqueConstraints']) && ! empty($options['uniqueConstraints'])) {
            foreach ($options['uniqueConstraints'] as $name => $definition) {
                $queryFields .= ', ' . $this->getUniqueConstraintDeclarationSQL($name, $definition);
            }
        }

329
        if (isset($options['primary']) && ! empty($options['primary'])) {
330
            $keyColumns = array_unique(array_values($options['primary']));
331 332 333
            $queryFields.= ', PRIMARY KEY('.implode(', ', $keyColumns).')';
        }

334 335 336 337 338 339
        if (isset($options['foreignKeys'])) {
            foreach ($options['foreignKeys'] as $foreignKey) {
                $queryFields.= ', '.$this->getForeignKeyDeclarationSQL($foreignKey);
            }
        }

340
        $query[] = 'CREATE TABLE ' . $name . ' (' . $queryFields . ')';
341

342 343
        if (isset($options['alter']) && true === $options['alter']) {
            return $query;
344
        }
345

346
        if (isset($options['indexes']) && ! empty($options['indexes'])) {
Benjamin Morel's avatar
Benjamin Morel committed
347
            foreach ($options['indexes'] as $indexDef) {
348
                $query[] = $this->getCreateIndexSQL($indexDef, $name);
349 350
            }
        }
351

352
        if (isset($options['unique']) && ! empty($options['unique'])) {
Benjamin Morel's avatar
Benjamin Morel committed
353
            foreach ($options['unique'] as $indexDef) {
354 355 356 357
                $query[] = $this->getCreateIndexSQL($indexDef, $name);
            }
        }

358 359 360 361
        return $query;
    }

    /**
362
     * {@inheritDoc}
363
     */
364
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
365 366 367 368
    {
        return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)')
                : ($length ? 'VARCHAR(' . $length . ')' : 'TEXT');
    }
369

Steve Müller's avatar
Steve Müller committed
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
    /**
     * {@inheritdoc}
     */
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
    {
        return 'BLOB';
    }

    /**
     * {@inheritdoc}
     */
    public function getBinaryMaxLength()
    {
        return 0;
    }

    /**
     * {@inheritdoc}
     */
    public function getBinaryDefaultLength()
    {
        return 0;
    }

394 395 396
    /**
     * {@inheritDoc}
     */
397
    public function getClobTypeDeclarationSQL(array $field)
398 399 400
    {
        return 'CLOB';
    }
401

402 403 404
    /**
     * {@inheritDoc}
     */
405
    public function getListTableConstraintsSQL($table)
406
    {
407
        $table = str_replace('.', '__', $table);
408

409
        return "SELECT sql FROM sqlite_master WHERE type='index' AND tbl_name = '$table' AND sql NOT NULL ORDER BY name";
410 411
    }

412 413 414
    /**
     * {@inheritDoc}
     */
415
    public function getListTableColumnsSQL($table, $currentDatabase = null)
416
    {
417
        $table = str_replace('.', '__', $table);
418

419
        return "PRAGMA table_info('$table')";
420 421
    }

422 423 424
    /**
     * {@inheritDoc}
     */
425
    public function getListTableIndexesSQL($table, $currentDatabase = null)
426
    {
427
        $table = str_replace('.', '__', $table);
428

429
        return "PRAGMA index_list('$table')";
430 431
    }

432 433 434
    /**
     * {@inheritDoc}
     */
435
    public function getListTablesSQL()
436
    {
jsor's avatar
jsor committed
437
        return "SELECT name FROM sqlite_master WHERE type = 'table' AND name != 'sqlite_sequence' AND name != 'geometry_columns' AND name != 'spatial_ref_sys' "
438 439 440 441
             . "UNION ALL SELECT name FROM sqlite_temp_master "
             . "WHERE type = 'table' ORDER BY name";
    }

442 443 444
    /**
     * {@inheritDoc}
     */
445
    public function getListViewsSQL($database)
446 447 448 449
    {
        return "SELECT name, sql FROM sqlite_master WHERE type='view' AND sql NOT NULL";
    }

450 451 452
    /**
     * {@inheritDoc}
     */
453
    public function getCreateViewSQL($name, $sql)
454 455 456 457
    {
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
    }

458 459 460
    /**
     * {@inheritDoc}
     */
461
    public function getDropViewSQL($name)
462 463 464 465
    {
        return 'DROP VIEW '. $name;
    }

466 467 468
    /**
     * {@inheritDoc}
     */
469 470 471 472
    public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey)
    {
        $query = parent::getAdvancedForeignKeyOptionsSQL($foreignKey);

473 474
        $query .= (($foreignKey->hasOption('deferrable') && $foreignKey->getOption('deferrable') !== false) ? ' ' : ' NOT ') . 'DEFERRABLE';
        $query .= ' INITIALLY ' . (($foreignKey->hasOption('deferred') && $foreignKey->getOption('deferred') !== false) ? 'DEFERRED' : 'IMMEDIATE');
475 476 477 478

        return $query;
    }

479 480 481
    /**
     * {@inheritDoc}
     */
482 483 484 485 486
    public function supportsIdentityColumns()
    {
        return true;
    }

487 488 489 490 491 492 493 494
    /**
     * {@inheritDoc}
     */
    public function supportsColumnCollation()
    {
        return true;
    }

495 496 497 498 499 500 501 502
    /**
     * {@inheritDoc}
     */
    public function supportsInlineColumnComments()
    {
        return true;
    }

503
    /**
504
     * {@inheritDoc}
505 506 507 508 509
     */
    public function getName()
    {
        return 'sqlite';
    }
510 511

    /**
512
     * {@inheritDoc}
513
     */
514
    public function getTruncateTableSQL($tableName, $cascade = false)
515
    {
516
        $tableName = str_replace('.', '__', $tableName);
517

518
        return 'DELETE FROM ' . $tableName;
519
    }
520 521

    /**
Benjamin Morel's avatar
Benjamin Morel committed
522
     * User-defined function for Sqlite that is used with PDO::sqliteCreateFunction().
523
     *
Benjamin Morel's avatar
Benjamin Morel committed
524
     * @param integer|float $value
525
     *
526 527 528 529 530 531 532 533
     * @return float
     */
    static public function udfSqrt($value)
    {
        return sqrt($value);
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
534
     * User-defined function for Sqlite that implements MOD(a, b).
535 536 537 538 539
     *
     * @param integer $a
     * @param integer $b
     *
     * @return integer
540 541 542 543 544
     */
    static public function udfMod($a, $b)
    {
        return ($a % $b);
    }
545 546

    /**
Benjamin Morel's avatar
Benjamin Morel committed
547 548
     * @param string  $str
     * @param string  $substr
549 550 551
     * @param integer $offset
     *
     * @return integer
552 553 554
     */
    static public function udfLocate($str, $substr, $offset = 0)
    {
555 556 557
        // SQL's LOCATE function works on 1-based positions, while PHP's strpos works on 0-based positions.
        // So we have to make them compatible if an offset is given.
        if ($offset > 0) {
Steve Müller's avatar
Steve Müller committed
558
            $offset -= 1;
559 560
        }

561
        $pos = strpos($str, $substr, $offset);
562

563
        if ($pos !== false) {
564
            return $pos + 1;
565
        }
566

567 568
        return 0;
    }
569

570 571 572
    /**
     * {@inheritDoc}
     */
573 574 575 576
    public function getForUpdateSql()
    {
        return '';
    }
577

578 579 580 581 582
    /**
     * {@inheritDoc}
     */
    public function getInlineColumnCommentSQL($comment)
    {
Steve Müller's avatar
Steve Müller committed
583
        return '--' . str_replace("\n", "\n--", $comment) . "\n";
584 585
    }

586 587 588
    /**
     * {@inheritDoc}
     */
589 590 591
    protected function initializeDoctrineTypeMappings()
    {
        $this->doctrineTypeMapping = array(
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
            'boolean'          => 'boolean',
            'tinyint'          => 'boolean',
            'smallint'         => 'smallint',
            'mediumint'        => 'integer',
            'int'              => 'integer',
            'integer'          => 'integer',
            'serial'           => 'integer',
            'bigint'           => 'bigint',
            'bigserial'        => 'bigint',
            'clob'             => 'text',
            'tinytext'         => 'text',
            'mediumtext'       => 'text',
            'longtext'         => 'text',
            'text'             => 'text',
            'varchar'          => 'string',
607
            'longvarchar'      => 'string',
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
            'varchar2'         => 'string',
            'nvarchar'         => 'string',
            'image'            => 'string',
            'ntext'            => 'string',
            'char'             => 'string',
            'date'             => 'date',
            'datetime'         => 'datetime',
            'timestamp'        => 'datetime',
            'time'             => 'time',
            'float'            => 'float',
            'double'           => 'float',
            'double precision' => 'float',
            'real'             => 'float',
            'decimal'          => 'decimal',
            'numeric'          => 'decimal',
623
            'blob'             => 'blob',
624 625
        );
    }
626

627 628 629
    /**
     * {@inheritDoc}
     */
630 631 632 633
    protected function getReservedKeywordsClass()
    {
        return 'Doctrine\DBAL\Platforms\Keywords\SQLiteKeywords';
    }
634

635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
    /**
     * {@inheritDoc}
     */
    protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff)
    {
        if ( ! $diff->fromTable instanceof Table) {
            throw new DBALException('Sqlite platform requires for alter table the table diff with reference to original table schema');
        }

        $sql = array();
        foreach ($diff->fromTable->getIndexes() as $index) {
            if ( ! $index->isPrimary()) {
                $sql[] = $this->getDropIndexSQL($index, $diff->name);
            }
        }

        return $sql;
    }

    /**
     * {@inheritDoc}
     */
    protected function getPostAlterTableIndexForeignKeySQL(TableDiff $diff)
    {
        if ( ! $diff->fromTable instanceof Table) {
            throw new DBALException('Sqlite platform requires for alter table the table diff with reference to original table schema');
        }

        $sql = array();
664
        $tableName = $diff->newName ? $diff->getNewName(): $diff->getName($this);
Benjamin Morel's avatar
Benjamin Morel committed
665
        foreach ($this->getIndexesInAlteredTable($diff) as $index) {
666 667 668 669
            if ($index->isPrimary()) {
                continue;
            }

670
            $sql[] = $this->getCreateIndexSQL($index, $tableName->getQuotedName($this));
671 672 673 674
        }

        return $sql;
    }
675 676 677 678 679 680 681 682 683 684 685 686

    /**
     * {@inheritDoc}
     */
    protected function doModifyLimitQuery($query, $limit, $offset)
    {
        if (null === $limit && null !== $offset) {
            return $query . ' LIMIT -1 OFFSET ' . $offset;
        }

        return parent::doModifyLimitQuery($query, $limit, $offset);
    }
687

688
    /**
689
     * {@inheritDoc}
690 691 692 693 694
     */
    public function getBlobTypeDeclarationSQL(array $field)
    {
        return 'BLOB';
    }
695

696 697 698
    /**
     * {@inheritDoc}
     */
699 700
    public function getTemporaryTableName($tableName)
    {
701
        $tableName = str_replace('.', '__', $tableName);
702

703 704
        return $tableName;
    }
705 706

    /**
707 708
     * {@inheritDoc}
     *
709 710 711 712 713 714 715 716 717 718
     * Sqlite Platform emulates schema by underscoring each dot and generating tables
     * into the default database.
     *
     * This hack is implemented to be able to use SQLite as testdriver when
     * using schema supporting databases.
     */
    public function canEmulateSchemas()
    {
        return true;
    }
719

720 721 722 723 724 725 726 727
    /**
     * {@inheritDoc}
     */
    public function supportsForeignKeyConstraints()
    {
        return false;
    }

728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
    /**
     * {@inheritDoc}
     */
    public function getCreatePrimaryKeySQL(Index $index, $table)
    {
        throw new DBALException('Sqlite platform does not support alter primary key.');
    }

    /**
     * {@inheritdoc}
     */
    public function getCreateForeignKeySQL(ForeignKeyConstraint $foreignKey, $table)
    {
        throw new DBALException('Sqlite platform does not support alter foreign key.');
    }

    /**
     * {@inheritdoc}
     */
    public function getDropForeignKeySQL($foreignKey, $table)
    {
        throw new DBALException('Sqlite platform does not support alter foreign key.');
    }

752 753 754 755 756 757 758
    /**
     * {@inheritDoc}
     */
    public function getCreateConstraintSQL(Constraint $constraint, $table)
    {
        throw new DBALException('Sqlite platform does not support alter constraint.');
    }
759 760 761 762 763 764 765 766 767 768

    /**
     * {@inheritDoc}
     */
    public function getCreateTableSQL(Table $table, $createFlags = null)
    {
        $createFlags = null === $createFlags ? self::CREATE_INDEXES | self::CREATE_FOREIGNKEYS : $createFlags;

        return parent::getCreateTableSQL($table, $createFlags);
    }
769

770 771 772 773 774 775 776
    /**
     * {@inheritDoc}
     */
    public function getListTableForeignKeysSQL($table, $database = null)
    {
        $table = str_replace('.', '__', $table);

777
        return "PRAGMA foreign_key_list('$table')";
778 779 780 781 782 783 784
    }

    /**
     * {@inheritDoc}
     */
    public function getAlterTableSQL(TableDiff $diff)
    {
785 786 787 788 789
        $sql = $this->getSimpleAlterTableSQL($diff);
        if (false !== $sql) {
            return $sql;
        }

790 791 792 793 794 795 796
        $fromTable = $diff->fromTable;
        if ( ! $fromTable instanceof Table) {
            throw new DBALException('Sqlite platform requires for alter table the table diff with reference to original table schema');
        }

        $table = clone $fromTable;

797 798 799
        $columns = array();
        $oldColumnNames = array();
        $newColumnNames = array();
800
        $columnSql = array();
801 802 803 804 805 806 807

        foreach ($table->getColumns() as $columnName => $column) {
            $columnName = strtolower($columnName);
            $columns[$columnName] = $column;
            $oldColumnNames[$columnName] = $newColumnNames[$columnName] = $column->getQuotedName($this);
        }

808 809 810 811 812
        foreach ($diff->removedColumns as $columnName => $column) {
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
                continue;
            }

813 814 815 816 817 818
            $columnName = strtolower($columnName);
            if (isset($columns[$columnName])) {
                unset($columns[$columnName]);
                unset($oldColumnNames[$columnName]);
                unset($newColumnNames[$columnName]);
            }
819 820 821 822 823 824 825
        }

        foreach ($diff->renamedColumns as $oldColumnName => $column) {
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
                continue;
            }

826 827 828 829 830 831 832 833 834 835
            $oldColumnName = strtolower($oldColumnName);
            if (isset($columns[$oldColumnName])) {
                unset($columns[$oldColumnName]);
            }

            $columns[strtolower($column->getName())] = $column;

            if (isset($newColumnNames[$oldColumnName])) {
                $newColumnNames[$oldColumnName] = $column->getQuotedName($this);
            }
836 837 838 839 840 841 842
        }

        foreach ($diff->changedColumns as $oldColumnName => $columnDiff) {
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
                continue;
            }

843 844
            if (isset($columns[$oldColumnName])) {
                unset($columns[$oldColumnName]);
845 846
            }

847
            $columns[strtolower($columnDiff->column->getName())] = $columnDiff->column;
848

849 850
            if (isset($newColumnNames[$oldColumnName])) {
                $newColumnNames[$oldColumnName] = $columnDiff->column->getQuotedName($this);
851 852 853
            }
        }

854 855 856 857
        foreach ($diff->addedColumns as $columnName => $column) {
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
                continue;
            }
858

859
            $columns[strtolower($columnName)] = $column;
860 861 862 863 864
        }

        $sql = array();
        $tableSql = array();
        if ( ! $this->onSchemaAlterTable($diff, $tableSql)) {
865 866
            $dataTable = new Table('__temp__'.$table->getName());

867
            $newTable = new Table($table->getQuotedName($this), $columns, $this->getPrimaryIndexInAlteredTable($diff), $this->getForeignKeysInAlteredTable($diff), 0, $table->getOptions());
868
            $newTable->addOption('alter', true);
869

870 871 872
            $sql = $this->getPreAlterTableIndexForeignKeySQL($diff);
            //$sql = array_merge($sql, $this->getCreateTableSQL($dataTable, 0));
            $sql[] = sprintf('CREATE TEMPORARY TABLE %s AS SELECT %s FROM %s', $dataTable->getQuotedName($this), implode(', ', $oldColumnNames), $table->getQuotedName($this));
873
            $sql[] = $this->getDropTableSQL($fromTable);
874 875 876 877 878 879

            $sql = array_merge($sql, $this->getCreateTableSQL($newTable));
            $sql[] = sprintf('INSERT INTO %s (%s) SELECT %s FROM %s', $newTable->getQuotedName($this), implode(', ', $newColumnNames), implode(', ', $oldColumnNames), $dataTable->getQuotedName($this));
            $sql[] = $this->getDropTableSQL($dataTable);

            if ($diff->newName && $diff->newName != $diff->name) {
880
                $renamedTable = $diff->getNewName();
881 882 883
                $sql[] = 'ALTER TABLE '.$newTable->getQuotedName($this).' RENAME TO '.$renamedTable->getQuotedName($this);
            }

884 885
            $sql = array_merge($sql, $this->getPostAlterTableIndexForeignKeySQL($diff));
        }
886 887 888 889

        return array_merge($sql, $tableSql, $columnSql);
    }

Benjamin Morel's avatar
Benjamin Morel committed
890 891 892 893 894
    /**
     * @param \Doctrine\DBAL\Schema\TableDiff $diff
     *
     * @return array|bool
     */
895 896
    private function getSimpleAlterTableSQL(TableDiff $diff)
    {
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919
        // Suppress changes on integer type autoincrement columns.
        foreach ($diff->changedColumns as $oldColumnName => $columnDiff) {
            if ( ! $columnDiff->fromColumn instanceof Column ||
                ! $columnDiff->column instanceof Column ||
                ! $columnDiff->column->getAutoincrement() ||
                ! (string) $columnDiff->column->getType() === 'Integer'
            ) {
                continue;
            }

            if ( ! $columnDiff->hasChanged('type') && $columnDiff->hasChanged('unsigned')) {
                unset($diff->changedColumns[$oldColumnName]);

                continue;
            }

            $fromColumnType = (string) $columnDiff->fromColumn->getType();

            if ($fromColumnType === 'SmallInt' || $fromColumnType === 'BigInt') {
                unset($diff->changedColumns[$oldColumnName]);
            }
        }

920 921 922
        if ( ! empty($diff->renamedColumns) || ! empty($diff->addedForeignKeys) || ! empty($diff->addedIndexes)
                || ! empty($diff->changedColumns) || ! empty($diff->changedForeignKeys) || ! empty($diff->changedIndexes)
                || ! empty($diff->removedColumns) || ! empty($diff->removedForeignKeys) || ! empty($diff->removedIndexes)
923
                || ! empty($diff->renamedIndexes)
924 925 926 927 928 929 930 931 932 933
        ) {
            return false;
        }

        $table = new Table($diff->name);

        $sql = array();
        $tableSql = array();
        $columnSql = array();

Benjamin Morel's avatar
Benjamin Morel committed
934
        foreach ($diff->addedColumns as $column) {
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
                continue;
            }

            $field = array_merge(array('unique' => null, 'autoincrement' => null, 'default' => null), $column->toArray());
            $type = (string) $field['type'];
            switch (true) {
                case isset($field['columnDefinition']) || $field['autoincrement'] || $field['unique']:
                case $type == 'DateTime' && $field['default'] == $this->getCurrentTimestampSQL():
                case $type == 'Date' && $field['default'] == $this->getCurrentDateSQL():
                case $type == 'Time' && $field['default'] == $this->getCurrentTimeSQL():
                    return false;
            }

            $field['name'] = $column->getQuotedName($this);
            if (strtolower($field['type']) == 'string' && $field['length'] === null) {
                $field['length'] = 255;
            }

            $sql[] = 'ALTER TABLE '.$table->getQuotedName($this).' ADD COLUMN '.$this->getColumnDeclarationSQL($field['name'], $field);
        }

        if ( ! $this->onSchemaAlterTable($diff, $tableSql)) {
            if ($diff->newName !== false) {
959
                $newTable = new Identifier($diff->newName);
960 961 962
                $sql[] = 'ALTER TABLE '.$table->getQuotedName($this).' RENAME TO '.$newTable->getQuotedName($this);
            }
        }
963 964 965 966

        return array_merge($sql, $tableSql, $columnSql);
    }

Benjamin Morel's avatar
Benjamin Morel committed
967 968 969 970 971
    /**
     * @param \Doctrine\DBAL\Schema\TableDiff $diff
     *
     * @return array
     */
972
    private function getColumnNamesInAlteredTable(TableDiff $diff)
973
    {
974
        $columns = array();
975

976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
        foreach ($diff->fromTable->getColumns() as $columnName => $column) {
            $columns[strtolower($columnName)] = $column->getName();
        }

        foreach ($diff->removedColumns as $columnName => $column) {
            $columnName = strtolower($columnName);
            if (isset($columns[$columnName])) {
                unset($columns[$columnName]);
            }
        }

        foreach ($diff->renamedColumns as $oldColumnName => $column) {
            $columnName = $column->getName();
            $columns[strtolower($oldColumnName)] = $columnName;
            $columns[strtolower($columnName)] = $columnName;
        }

        foreach ($diff->changedColumns as $oldColumnName => $columnDiff) {
            $columnName = $columnDiff->column->getName();
            $columns[strtolower($oldColumnName)] = $columnName;
            $columns[strtolower($columnName)] = $columnName;
        }

        foreach ($diff->addedColumns as $columnName => $column) {
            $columns[strtolower($columnName)] = $columnName;
        }

        return $columns;
    }

Benjamin Morel's avatar
Benjamin Morel committed
1006 1007 1008 1009 1010
    /**
     * @param \Doctrine\DBAL\Schema\TableDiff $diff
     *
     * @return \Doctrine\DBAL\Schema\Index[]
     */
1011 1012 1013 1014 1015 1016
    private function getIndexesInAlteredTable(TableDiff $diff)
    {
        $indexes = $diff->fromTable->getIndexes();
        $columnNames = $this->getColumnNamesInAlteredTable($diff);

        foreach ($indexes as $key => $index) {
1017 1018 1019 1020 1021 1022
            foreach ($diff->renamedIndexes as $oldIndexName => $renamedIndex) {
                if (strtolower($key) === strtolower($oldIndexName)) {
                    unset($indexes[$key]);
                }
            }

1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
            $changed = false;
            $indexColumns = array();
            foreach ($index->getColumns() as $columnName) {
                $normalizedColumnName = strtolower($columnName);
                if ( ! isset($columnNames[$normalizedColumnName])) {
                    unset($indexes[$key]);
                    continue 2;
                } else {
                    $indexColumns[] = $columnNames[$normalizedColumnName];
                    if ($columnName !== $columnNames[$normalizedColumnName]) {
                        $changed = true;
                    }
                }
            }

            if ($changed) {
                $indexes[$key] = new Index($index->getName(), $indexColumns, $index->isUnique(), $index->isPrimary(), $index->getFlags());
1040 1041 1042 1043
            }
        }

        foreach ($diff->removedIndexes as $index) {
1044 1045 1046
            $indexName = strtolower($index->getName());
            if (strlen($indexName) && isset($indexes[$indexName])) {
                unset($indexes[$indexName]);
1047 1048 1049
            }
        }

1050
        foreach (array_merge($diff->changedIndexes, $diff->addedIndexes, $diff->renamedIndexes) as $index) {
1051 1052 1053 1054 1055
            $indexName = strtolower($index->getName());
            if (strlen($indexName)) {
                $indexes[$indexName] = $index;
            } else {
                $indexes[] = $index;
1056 1057 1058
            }
        }

1059 1060 1061
        return $indexes;
    }

Benjamin Morel's avatar
Benjamin Morel committed
1062 1063 1064 1065 1066
    /**
     * @param \Doctrine\DBAL\Schema\TableDiff $diff
     *
     * @return array
     */
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
    private function getForeignKeysInAlteredTable(TableDiff $diff)
    {
        $foreignKeys = $diff->fromTable->getForeignKeys();
        $columnNames = $this->getColumnNamesInAlteredTable($diff);

        foreach ($foreignKeys as $key => $constraint) {
            $changed = false;
            $localColumns = array();
            foreach ($constraint->getLocalColumns() as $columnName) {
                $normalizedColumnName = strtolower($columnName);
                if ( ! isset($columnNames[$normalizedColumnName])) {
                    unset($foreignKeys[$key]);
                    continue 2;
                } else {
                    $localColumns[] = $columnNames[$normalizedColumnName];
                    if ($columnName !== $columnNames[$normalizedColumnName]) {
                        $changed = true;
                    }
                }
            }

            if ($changed) {
                $foreignKeys[$key] = new ForeignKeyConstraint($localColumns, $constraint->getForeignTableName(), $constraint->getForeignColumns(), $constraint->getName(), $constraint->getOptions());
            }
        }

        foreach ($diff->removedForeignKeys as $constraint) {
            $constraintName = strtolower($constraint->getName());
            if (strlen($constraintName) && isset($foreignKeys[$constraintName])) {
                unset($foreignKeys[$constraintName]);
            }
        }

        foreach (array_merge($diff->changedForeignKeys, $diff->addedForeignKeys) as $constraint) {
            $constraintName = strtolower($constraint->getName());
            if (strlen($constraintName)) {
                $foreignKeys[$constraintName] = $constraint;
            } else {
                $foreignKeys[] = $constraint;
            }
        }

        return $foreignKeys;
    }

Benjamin Morel's avatar
Benjamin Morel committed
1112 1113 1114 1115 1116
    /**
     * @param \Doctrine\DBAL\Schema\TableDiff $diff
     *
     * @return array
     */
1117 1118 1119 1120 1121
    private function getPrimaryIndexInAlteredTable(TableDiff $diff)
    {
        $primaryIndex = array();

        foreach ($this->getIndexesInAlteredTable($diff) as $index) {
1122
            if ($index->isPrimary()) {
1123
                $primaryIndex = array($index->getName() => $index);
1124 1125 1126 1127 1128
            }
        }

        return $primaryIndex;
    }
1129
}