SqlitePlatform.php 33.8 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
        $table = $this->quoteStringLiteral($table);
409

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

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

421
        return "PRAGMA table_info($table)";
422 423
    }

424 425 426
    /**
     * {@inheritDoc}
     */
427
    public function getListTableIndexesSQL($table, $currentDatabase = null)
428
    {
429
        $table = str_replace('.', '__', $table);
430
        $table = $this->quoteStringLiteral($table);
431

432
        return "PRAGMA index_list($table)";
433 434
    }

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

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

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

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

469 470 471
    /**
     * {@inheritDoc}
     */
472 473 474 475
    public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey)
    {
        $query = parent::getAdvancedForeignKeyOptionsSQL($foreignKey);

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

        return $query;
    }

482 483 484
    /**
     * {@inheritDoc}
     */
485 486 487 488 489
    public function supportsIdentityColumns()
    {
        return true;
    }

490 491 492 493 494 495 496 497
    /**
     * {@inheritDoc}
     */
    public function supportsColumnCollation()
    {
        return true;
    }

498 499 500 501 502 503 504 505
    /**
     * {@inheritDoc}
     */
    public function supportsInlineColumnComments()
    {
        return true;
    }

506
    /**
507
     * {@inheritDoc}
508 509 510 511 512
     */
    public function getName()
    {
        return 'sqlite';
    }
513 514

    /**
515
     * {@inheritDoc}
516
     */
517
    public function getTruncateTableSQL($tableName, $cascade = false)
518
    {
519 520
        $tableIdentifier = new Identifier($tableName);
        $tableName = str_replace('.', '__', $tableIdentifier->getQuotedName($this));
521

522
        return 'DELETE FROM ' . $tableName;
523
    }
524 525

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

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

    /**
Benjamin Morel's avatar
Benjamin Morel committed
551 552
     * @param string  $str
     * @param string  $substr
553 554 555
     * @param integer $offset
     *
     * @return integer
556 557 558
     */
    static public function udfLocate($str, $substr, $offset = 0)
    {
559 560 561
        // 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
562
            $offset -= 1;
563 564
        }

565
        $pos = strpos($str, $substr, $offset);
566

567
        if ($pos !== false) {
568
            return $pos + 1;
569
        }
570

571 572
        return 0;
    }
573

574 575 576
    /**
     * {@inheritDoc}
     */
577 578 579 580
    public function getForUpdateSql()
    {
        return '';
    }
581

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

590 591 592
    /**
     * {@inheritDoc}
     */
593 594 595
    protected function initializeDoctrineTypeMappings()
    {
        $this->doctrineTypeMapping = array(
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
            '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',
611
            'longvarchar'      => 'string',
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
            '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',
627
            'blob'             => 'blob',
628 629
        );
    }
630

631 632 633
    /**
     * {@inheritDoc}
     */
634 635 636 637
    protected function getReservedKeywordsClass()
    {
        return 'Doctrine\DBAL\Platforms\Keywords\SQLiteKeywords';
    }
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 664 665 666 667
    /**
     * {@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();
668
        $tableName = $diff->newName ? $diff->getNewName(): $diff->getName($this);
Benjamin Morel's avatar
Benjamin Morel committed
669
        foreach ($this->getIndexesInAlteredTable($diff) as $index) {
670 671 672 673
            if ($index->isPrimary()) {
                continue;
            }

674
            $sql[] = $this->getCreateIndexSQL($index, $tableName->getQuotedName($this));
675 676 677 678
        }

        return $sql;
    }
679 680 681 682 683 684 685 686 687 688 689 690

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

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

692
    /**
693
     * {@inheritDoc}
694 695 696 697 698
     */
    public function getBlobTypeDeclarationSQL(array $field)
    {
        return 'BLOB';
    }
699

700 701 702
    /**
     * {@inheritDoc}
     */
703 704
    public function getTemporaryTableName($tableName)
    {
705
        $tableName = str_replace('.', '__', $tableName);
706

707 708
        return $tableName;
    }
709 710

    /**
711 712
     * {@inheritDoc}
     *
713 714 715 716 717 718 719 720 721 722
     * 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;
    }
723

724 725 726 727 728 729 730 731
    /**
     * {@inheritDoc}
     */
    public function supportsForeignKeyConstraints()
    {
        return false;
    }

732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
    /**
     * {@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.');
    }

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

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

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

774 775 776 777 778 779
    /**
     * {@inheritDoc}
     */
    public function getListTableForeignKeysSQL($table, $database = null)
    {
        $table = str_replace('.', '__', $table);
780
        $table = $this->quoteStringLiteral($table);
781

782
        return "PRAGMA foreign_key_list($table)";
783 784 785 786 787 788 789
    }

    /**
     * {@inheritDoc}
     */
    public function getAlterTableSQL(TableDiff $diff)
    {
790 791 792 793 794
        $sql = $this->getSimpleAlterTableSQL($diff);
        if (false !== $sql) {
            return $sql;
        }

795 796 797 798 799 800 801
        $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;

802 803 804
        $columns = array();
        $oldColumnNames = array();
        $newColumnNames = array();
805
        $columnSql = array();
806 807 808 809 810 811 812

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

813 814 815 816 817
        foreach ($diff->removedColumns as $columnName => $column) {
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
                continue;
            }

818 819 820 821 822 823
            $columnName = strtolower($columnName);
            if (isset($columns[$columnName])) {
                unset($columns[$columnName]);
                unset($oldColumnNames[$columnName]);
                unset($newColumnNames[$columnName]);
            }
824 825 826 827 828 829 830
        }

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

831 832 833 834 835 836 837 838 839 840
            $oldColumnName = strtolower($oldColumnName);
            if (isset($columns[$oldColumnName])) {
                unset($columns[$oldColumnName]);
            }

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

            if (isset($newColumnNames[$oldColumnName])) {
                $newColumnNames[$oldColumnName] = $column->getQuotedName($this);
            }
841 842 843 844 845 846 847
        }

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

848 849
            if (isset($columns[$oldColumnName])) {
                unset($columns[$oldColumnName]);
850 851
            }

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

854 855
            if (isset($newColumnNames[$oldColumnName])) {
                $newColumnNames[$oldColumnName] = $columnDiff->column->getQuotedName($this);
856 857 858
            }
        }

859 860 861 862
        foreach ($diff->addedColumns as $columnName => $column) {
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
                continue;
            }
863

864
            $columns[strtolower($columnName)] = $column;
865 866 867 868 869
        }

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

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

875 876 877
            $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));
878
            $sql[] = $this->getDropTableSQL($fromTable);
879 880 881 882 883 884

            $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) {
885
                $renamedTable = $diff->getNewName();
886 887 888
                $sql[] = 'ALTER TABLE '.$newTable->getQuotedName($this).' RENAME TO '.$renamedTable->getQuotedName($this);
            }

889 890
            $sql = array_merge($sql, $this->getPostAlterTableIndexForeignKeySQL($diff));
        }
891 892 893 894

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

Benjamin Morel's avatar
Benjamin Morel committed
895 896 897 898 899
    /**
     * @param \Doctrine\DBAL\Schema\TableDiff $diff
     *
     * @return array|bool
     */
900 901
    private function getSimpleAlterTableSQL(TableDiff $diff)
    {
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
        // 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]);
            }
        }

925 926 927
        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)
928
                || ! empty($diff->renamedIndexes)
929 930 931 932 933 934 935 936 937 938
        ) {
            return false;
        }

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

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

Benjamin Morel's avatar
Benjamin Morel committed
939
        foreach ($diff->addedColumns as $column) {
940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
            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) {
964
                $newTable = new Identifier($diff->newName);
965 966 967
                $sql[] = 'ALTER TABLE '.$table->getQuotedName($this).' RENAME TO '.$newTable->getQuotedName($this);
            }
        }
968 969 970 971

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

Benjamin Morel's avatar
Benjamin Morel committed
972 973 974 975 976
    /**
     * @param \Doctrine\DBAL\Schema\TableDiff $diff
     *
     * @return array
     */
977
    private function getColumnNamesInAlteredTable(TableDiff $diff)
978
    {
979
        $columns = array();
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 1006 1007 1008 1009 1010
        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
1011 1012 1013 1014 1015
    /**
     * @param \Doctrine\DBAL\Schema\TableDiff $diff
     *
     * @return \Doctrine\DBAL\Schema\Index[]
     */
1016 1017 1018 1019 1020 1021
    private function getIndexesInAlteredTable(TableDiff $diff)
    {
        $indexes = $diff->fromTable->getIndexes();
        $columnNames = $this->getColumnNamesInAlteredTable($diff);

        foreach ($indexes as $key => $index) {
1022 1023 1024 1025 1026 1027
            foreach ($diff->renamedIndexes as $oldIndexName => $renamedIndex) {
                if (strtolower($key) === strtolower($oldIndexName)) {
                    unset($indexes[$key]);
                }
            }

1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
            $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());
1045 1046 1047 1048
            }
        }

        foreach ($diff->removedIndexes as $index) {
1049 1050 1051
            $indexName = strtolower($index->getName());
            if (strlen($indexName) && isset($indexes[$indexName])) {
                unset($indexes[$indexName]);
1052 1053 1054
            }
        }

1055
        foreach (array_merge($diff->changedIndexes, $diff->addedIndexes, $diff->renamedIndexes) as $index) {
1056 1057 1058 1059 1060
            $indexName = strtolower($index->getName());
            if (strlen($indexName)) {
                $indexes[$indexName] = $index;
            } else {
                $indexes[] = $index;
1061 1062 1063
            }
        }

1064 1065 1066
        return $indexes;
    }

Benjamin Morel's avatar
Benjamin Morel committed
1067 1068 1069 1070 1071
    /**
     * @param \Doctrine\DBAL\Schema\TableDiff $diff
     *
     * @return array
     */
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 1112 1113 1114 1115 1116
    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
1117 1118 1119 1120 1121
    /**
     * @param \Doctrine\DBAL\Schema\TableDiff $diff
     *
     * @return array
     */
1122 1123 1124 1125 1126
    private function getPrimaryIndexInAlteredTable(TableDiff $diff)
    {
        $primaryIndex = array();

        foreach ($this->getIndexesInAlteredTable($diff) as $index) {
1127
            if ($index->isPrimary()) {
1128
                $primaryIndex = array($index->getName() => $index);
1129 1130 1131 1132 1133
            }
        }

        return $primaryIndex;
    }
1134
}