SqlitePlatform.php 33.4 KB
Newer Older
1 2
<?php

3
namespace Doctrine\DBAL\Platforms;
4

5
use Doctrine\DBAL\DBALException;
6
use Doctrine\DBAL\Schema\Column;
7
use Doctrine\DBAL\Schema\Constraint;
8
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
9
use Doctrine\DBAL\Schema\Identifier;
10 11 12
use Doctrine\DBAL\Schema\Index;
use Doctrine\DBAL\Schema\Table;
use Doctrine\DBAL\Schema\TableDiff;
13
use Doctrine\DBAL\TransactionIsolationLevel;
14
use Doctrine\DBAL\Types;
15 16 17 18 19 20 21 22 23 24 25
use function array_merge;
use function array_unique;
use function array_values;
use function implode;
use function is_numeric;
use function sprintf;
use function sqrt;
use function str_replace;
use function strlen;
use function strpos;
use function strtolower;
26

27
/**
28 29
 * The SqlitePlatform class describes the specifics and dialects of the SQLite
 * database platform.
30
 *
Benjamin Morel's avatar
Benjamin Morel committed
31
 * @todo   Rename: SQLitePlatform
32
 */
33
class SqlitePlatform extends AbstractPlatform
34 35
{
    /**
36
     * {@inheritDoc}
37 38 39
     */
    public function getRegexpExpression()
    {
40
        return 'REGEXP';
41 42 43
    }

    /**
44
     * {@inheritDoc}
45 46 47 48 49 50 51 52 53 54 55 56 57 58
     */
    public function getNowExpression($type = 'timestamp')
    {
        switch ($type) {
            case 'time':
                return 'time(\'now\')';
            case 'date':
                return 'date(\'now\')';
            case 'timestamp':
            default:
                return 'datetime(\'now\')';
        }
    }

59
    /**
60
     * {@inheritDoc}
61
     */
62
    public function getTrimExpression($str, $pos = TrimMode::UNSPECIFIED, $char = false)
63
    {
64
        $trimChar = $char !== false ? (', ' . $char) : '';
65

66
        switch ($pos) {
67
            case TrimMode::LEADING:
68 69 70
                $trimFn = 'LTRIM';
                break;

71
            case TrimMode::TRAILING:
72 73 74 75 76
                $trimFn = 'RTRIM';
                break;

            default:
                $trimFn = 'TRIM';
77 78 79 80 81
        }

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

82
    /**
83
     * {@inheritDoc}
84 85 86 87 88 89 90 91
     *
     * 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 . ')';
        }
92

93 94 95
        return 'SUBSTR(' . $value . ', ' . $position . ', LENGTH(' . $value . '))';
    }

96
    /**
97
     * {@inheritDoc}
98 99 100
     */
    public function getLocateExpression($str, $substr, $startPos = false)
    {
101 102
        if ($startPos === false) {
            return 'LOCATE(' . $str . ', ' . $substr . ')';
103
        }
104

105
        return 'LOCATE(' . $str . ', ' . $substr . ', ' . $startPos . ')';
106 107
    }

108
    /**
109
     * {@inheritdoc}
110
     */
111
    protected function getDateArithmeticIntervalExpression($date, $operator, $interval, $unit)
112
    {
113
        switch ($unit) {
114 115 116
            case DateIntervalUnit::SECOND:
            case DateIntervalUnit::MINUTE:
            case DateIntervalUnit::HOUR:
117
                return 'DATETIME(' . $date . ",'" . $operator . $interval . ' ' . $unit . "')";
118

119 120
            default:
                switch ($unit) {
121
                    case DateIntervalUnit::WEEK:
122
                        $interval *= 7;
123
                        $unit      = DateIntervalUnit::DAY;
124 125
                        break;

126
                    case DateIntervalUnit::QUARTER:
127
                        $interval *= 3;
128
                        $unit      = DateIntervalUnit::MONTH;
129 130 131
                        break;
                }

Fogs's avatar
Fogs committed
132
                if (! is_numeric($interval)) {
133 134 135
                    $interval = "' || " . $interval . " || '";
                }

136
                return 'DATE(' . $date . ",'" . $operator . $interval . ' ' . $unit . "')";
137
        }
138 139
    }

140 141 142
    /**
     * {@inheritDoc}
     */
143
    public function getDateDiffExpression($date1, $date2)
144
    {
145
        return sprintf("JULIANDAY(%s, 'start of day') - JULIANDAY(%s, 'start of day')", $date1, $date2);
146 147
    }

148 149 150
    /**
     * {@inheritDoc}
     */
151
    protected function _getTransactionIsolationLevelSQL($level)
romanb's avatar
romanb committed
152 153
    {
        switch ($level) {
154
            case TransactionIsolationLevel::READ_UNCOMMITTED:
romanb's avatar
romanb committed
155
                return 0;
156 157 158
            case TransactionIsolationLevel::READ_COMMITTED:
            case TransactionIsolationLevel::REPEATABLE_READ:
            case TransactionIsolationLevel::SERIALIZABLE:
romanb's avatar
romanb committed
159 160
                return 1;
            default:
161
                return parent::_getTransactionIsolationLevelSQL($level);
romanb's avatar
romanb committed
162 163
        }
    }
164

165 166 167
    /**
     * {@inheritDoc}
     */
168
    public function getSetTransactionIsolationSQL($level)
romanb's avatar
romanb committed
169
    {
170
        return 'PRAGMA read_uncommitted = ' . $this->_getTransactionIsolationLevelSQL($level);
romanb's avatar
romanb committed
171
    }
172

173
    /**
174
     * {@inheritDoc}
175
     */
176 177
    public function prefersIdentityColumns()
    {
178 179
        return true;
    }
180 181

    /**
182
     * {@inheritDoc}
183
     */
184
    public function getBooleanTypeDeclarationSQL(array $field)
185 186 187
    {
        return 'BOOLEAN';
    }
188

189
    /**
190
     * {@inheritDoc}
191
     */
192
    public function getIntegerTypeDeclarationSQL(array $field)
193
    {
194
        return 'INTEGER' . $this->_getCommonIntegerTypeDeclarationSQL($field);
195 196
    }

197
    /**
198
     * {@inheritDoc}
199
     */
200
    public function getBigIntTypeDeclarationSQL(array $field)
201
    {
202
        //  SQLite autoincrement is implicit for INTEGER PKs, but not for BIGINT fields.
203
        if (! empty($field['autoincrement'])) {
204 205 206
            return $this->getIntegerTypeDeclarationSQL($field);
        }

207
        return 'BIGINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
208 209
    }

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

220
        return 'TINYINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
221 222
    }

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

233
        return 'SMALLINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
234 235
    }

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

246
        return 'MEDIUMINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
247 248
    }

249
    /**
250
     * {@inheritDoc}
251
     */
252
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
253 254 255
    {
        return 'DATETIME';
    }
256

257
    /**
258
     * {@inheritDoc}
259
     */
260
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
261 262 263
    {
        return 'DATE';
    }
264

265
    /**
266
     * {@inheritDoc}
267
     */
268
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
269 270 271 272
    {
        return 'TIME';
    }

273
    /**
274
     * {@inheritDoc}
275
     */
276
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
277
    {
278
        // sqlite autoincrement is only possible for the primary key
279
        if (! empty($columnDef['autoincrement'])) {
280
            return ' PRIMARY KEY AUTOINCREMENT';
281 282
        }

283
        return ! empty($columnDef['unsigned']) ? ' UNSIGNED' : '';
284 285
    }

286 287 288 289 290 291
    /**
     * {@inheritDoc}
     */
    public function getForeignKeyDeclarationSQL(ForeignKeyConstraint $foreignKey)
    {
        return parent::getForeignKeyDeclarationSQL(new ForeignKeyConstraint(
292 293 294
            $foreignKey->getQuotedLocalColumns($this),
            str_replace('.', '__', $foreignKey->getQuotedForeignTableName($this)),
            $foreignKey->getQuotedForeignColumns($this),
295 296 297 298 299
            $foreignKey->getName(),
            $foreignKey->getOptions()
        ));
    }

300
    /**
301
     * {@inheritDoc}
302
     */
303
    protected function _getCreateTableSQL($tableName, array $columns, array $options = [])
304
    {
Guilherme Blanco's avatar
Guilherme Blanco committed
305
        $tableName   = str_replace('.', '__', $tableName);
306
        $queryFields = $this->getColumnDeclarationListSQL($columns);
307

308 309 310 311 312 313
        if (isset($options['uniqueConstraints']) && ! empty($options['uniqueConstraints'])) {
            foreach ($options['uniqueConstraints'] as $name => $definition) {
                $queryFields .= ', ' . $this->getUniqueConstraintDeclarationSQL($name, $definition);
            }
        }

Timo Bakx's avatar
Timo Bakx committed
314
        $queryFields .= $this->getNonAutoincrementPrimaryKeyDefinition($columns, $options);
315

316 317
        if (isset($options['foreignKeys'])) {
            foreach ($options['foreignKeys'] as $foreignKey) {
318
                $queryFields .= ', ' . $this->getForeignKeyDeclarationSQL($foreignKey);
319 320 321
            }
        }

322
        $query = ['CREATE TABLE ' . $tableName . ' (' . $queryFields . ')'];
323

324
        if (isset($options['alter']) && $options['alter'] === true) {
325
            return $query;
326
        }
327

328
        if (isset($options['indexes']) && ! empty($options['indexes'])) {
Benjamin Morel's avatar
Benjamin Morel committed
329
            foreach ($options['indexes'] as $indexDef) {
330
                $query[] = $this->getCreateIndexSQL($indexDef, $tableName);
331 332
            }
        }
333

334
        if (isset($options['unique']) && ! empty($options['unique'])) {
Benjamin Morel's avatar
Benjamin Morel committed
335
            foreach ($options['unique'] as $indexDef) {
336
                $query[] = $this->getCreateIndexSQL($indexDef, $tableName);
337 338 339
            }
        }

340 341 342
        return $query;
    }

Timo Bakx's avatar
Timo Bakx committed
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
    /**
     * Generate a PRIMARY KEY definition if no autoincrement value is used
     *
     * @param string[] $columns
     * @param mixed[]  $options
     */
    private function getNonAutoincrementPrimaryKeyDefinition(array $columns, array $options) : string
    {
        if (empty($options['primary'])) {
            return '';
        }

        $keyColumns = array_unique(array_values($options['primary']));

        foreach ($keyColumns as $keyColumn) {
            if (isset($columns[$keyColumn]['autoincrement']) && ! empty($columns[$keyColumn]['autoincrement'])) {
                return '';
            }
        }

        return ', PRIMARY KEY(' . implode(', ', $keyColumns) . ')';
    }

366
    /**
367
     * {@inheritDoc}
368
     */
369
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
370
    {
371 372
        return $fixed
            ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)')
Guilherme Blanco's avatar
Guilherme Blanco committed
373
            : ($length ? 'VARCHAR(' . $length . ')' : 'TEXT');
374
    }
375

Steve Müller's avatar
Steve Müller committed
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
    /**
     * {@inheritdoc}
     */
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
    {
        return 'BLOB';
    }

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

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

400 401 402
    /**
     * {@inheritDoc}
     */
403
    public function getClobTypeDeclarationSQL(array $field)
404 405 406
    {
        return 'CLOB';
    }
407

408 409 410
    /**
     * {@inheritDoc}
     */
411
    public function getListTableConstraintsSQL($table)
412
    {
413
        $table = str_replace('.', '__', $table);
414

415 416 417 418
        return sprintf(
            "SELECT sql FROM sqlite_master WHERE type='index' AND tbl_name = %s AND sql NOT NULL ORDER BY name",
            $this->quoteStringLiteral($table)
        );
419 420
    }

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

428
        return sprintf('PRAGMA table_info(%s)', $this->quoteStringLiteral($table));
429 430
    }

431 432 433
    /**
     * {@inheritDoc}
     */
434
    public function getListTableIndexesSQL($table, $currentDatabase = null)
435
    {
436
        $table = str_replace('.', '__', $table);
437

438
        return sprintf('PRAGMA index_list(%s)', $this->quoteStringLiteral($table));
439 440
    }

441 442 443
    /**
     * {@inheritDoc}
     */
444
    public function getListTablesSQL()
445
    {
jsor's avatar
jsor committed
446
        return "SELECT name FROM sqlite_master WHERE type = 'table' AND name != 'sqlite_sequence' AND name != 'geometry_columns' AND name != 'spatial_ref_sys' "
447
             . 'UNION ALL SELECT name FROM sqlite_temp_master '
448 449 450
             . "WHERE type = 'table' ORDER BY name";
    }

451 452 453
    /**
     * {@inheritDoc}
     */
454
    public function getListViewsSQL($database)
455 456 457 458
    {
        return "SELECT name, sql FROM sqlite_master WHERE type='view' AND sql NOT NULL";
    }

459 460 461
    /**
     * {@inheritDoc}
     */
462
    public function getCreateViewSQL($name, $sql)
463 464 465 466
    {
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
    }

467 468 469
    /**
     * {@inheritDoc}
     */
470
    public function getDropViewSQL($name)
471
    {
472
        return 'DROP VIEW ' . $name;
473 474
    }

475 476 477
    /**
     * {@inheritDoc}
     */
478 479 480 481
    public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey)
    {
        $query = parent::getAdvancedForeignKeyOptionsSQL($foreignKey);

482 483
        $query .= ($foreignKey->hasOption('deferrable') && $foreignKey->getOption('deferrable') !== false ? ' ' : ' NOT ') . 'DEFERRABLE';
        $query .= ' INITIALLY ' . ($foreignKey->hasOption('deferred') && $foreignKey->getOption('deferred') !== false ? 'DEFERRED' : 'IMMEDIATE');
484 485 486 487

        return $query;
    }

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

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

504 505 506 507 508 509 510 511
    /**
     * {@inheritDoc}
     */
    public function supportsInlineColumnComments()
    {
        return true;
    }

512
    /**
513
     * {@inheritDoc}
514 515 516 517 518
     */
    public function getName()
    {
        return 'sqlite';
    }
519 520

    /**
521
     * {@inheritDoc}
522
     */
523
    public function getTruncateTableSQL($tableName, $cascade = false)
524
    {
525
        $tableIdentifier = new Identifier($tableName);
526
        $tableName       = str_replace('.', '__', $tableIdentifier->getQuotedName($this));
527

528
        return 'DELETE FROM ' . $tableName;
529
    }
530 531

    /**
Benjamin Morel's avatar
Benjamin Morel committed
532
     * User-defined function for Sqlite that is used with PDO::sqliteCreateFunction().
533
     *
534
     * @param int|float $value
535
     *
536 537
     * @return float
     */
538
    public static function udfSqrt($value)
539 540 541 542 543
    {
        return sqrt($value);
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
544
     * User-defined function for Sqlite that implements MOD(a, b).
545
     *
546 547
     * @param int $a
     * @param int $b
548
     *
549
     * @return int
550
     */
551
    public static function udfMod($a, $b)
552
    {
553
        return $a % $b;
554
    }
555 556

    /**
557 558 559
     * @param string $str
     * @param string $substr
     * @param int    $offset
560
     *
561
     * @return int
562
     */
563
    public static function udfLocate($str, $substr, $offset = 0)
564
    {
565 566 567
        // 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
568
            $offset -= 1;
569 570
        }

571
        $pos = strpos($str, $substr, $offset);
572

573
        if ($pos !== false) {
574
            return $pos + 1;
575
        }
576

577 578
        return 0;
    }
579

580 581 582
    /**
     * {@inheritDoc}
     */
583 584 585 586
    public function getForUpdateSql()
    {
        return '';
    }
587

588 589 590 591 592
    /**
     * {@inheritDoc}
     */
    public function getInlineColumnCommentSQL($comment)
    {
Steve Müller's avatar
Steve Müller committed
593
        return '--' . str_replace("\n", "\n--", $comment) . "\n";
594 595
    }

596 597 598
    /**
     * {@inheritDoc}
     */
599 600
    protected function initializeDoctrineTypeMappings()
    {
601
        $this->doctrineTypeMapping = [
602 603
            'bigint'           => 'bigint',
            'bigserial'        => 'bigint',
604 605
            'blob'             => 'blob',
            'boolean'          => 'boolean',
606
            'char'             => 'string',
607
            'clob'             => 'text',
608 609
            'date'             => 'date',
            'datetime'         => 'datetime',
610
            'decimal'          => 'decimal',
611 612
            'double'           => 'float',
            'double precision' => 'float',
613 614 615 616 617 618 619 620 621
            'float'            => 'float',
            'image'            => 'string',
            'int'              => 'integer',
            'integer'          => 'integer',
            'longtext'         => 'text',
            'longvarchar'      => 'string',
            'mediumint'        => 'integer',
            'mediumtext'       => 'text',
            'ntext'            => 'string',
622
            'numeric'          => 'decimal',
623 624 625 626
            'nvarchar'         => 'string',
            'real'             => 'float',
            'serial'           => 'integer',
            'smallint'         => 'smallint',
627
            'string'           => 'string',
628 629 630 631 632 633 634
            'text'             => 'text',
            'time'             => 'time',
            'timestamp'        => 'datetime',
            'tinyint'          => 'boolean',
            'tinytext'         => 'text',
            'varchar'          => 'string',
            'varchar2'         => 'string',
635
        ];
636
    }
637

638 639 640
    /**
     * {@inheritDoc}
     */
641 642
    protected function getReservedKeywordsClass()
    {
643
        return Keywords\SQLiteKeywords::class;
644
    }
645

646 647 648 649 650
    /**
     * {@inheritDoc}
     */
    protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff)
    {
651
        if (! $diff->fromTable instanceof Table) {
652 653 654
            throw new DBALException('Sqlite platform requires for alter table the table diff with reference to original table schema');
        }

655
        $sql = [];
656
        foreach ($diff->fromTable->getIndexes() as $index) {
657 658
            if ($index->isPrimary()) {
                continue;
659
            }
660 661

            $sql[] = $this->getDropIndexSQL($index, $diff->name);
662 663 664 665 666 667 668 669 670 671
        }

        return $sql;
    }

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

676
        $sql       = [];
677
        $tableName = $diff->newName ? $diff->getNewName(): $diff->getName($this);
Benjamin Morel's avatar
Benjamin Morel committed
678
        foreach ($this->getIndexesInAlteredTable($diff) as $index) {
679 680 681 682
            if ($index->isPrimary()) {
                continue;
            }

683
            $sql[] = $this->getCreateIndexSQL($index, $tableName->getQuotedName($this));
684 685 686 687
        }

        return $sql;
    }
688 689 690 691 692 693

    /**
     * {@inheritDoc}
     */
    protected function doModifyLimitQuery($query, $limit, $offset)
    {
694
        if ($limit === null && $offset > 0) {
695 696 697 698 699
            return $query . ' LIMIT -1 OFFSET ' . $offset;
        }

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

701
    /**
702
     * {@inheritDoc}
703 704 705 706 707
     */
    public function getBlobTypeDeclarationSQL(array $field)
    {
        return 'BLOB';
    }
708

709 710 711
    /**
     * {@inheritDoc}
     */
712 713
    public function getTemporaryTableName($tableName)
    {
714
        $tableName = str_replace('.', '__', $tableName);
715

716 717
        return $tableName;
    }
718 719

    /**
720 721
     * {@inheritDoc}
     *
722 723 724 725 726 727 728 729 730 731
     * 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;
    }
732

733 734 735 736 737 738 739 740
    /**
     * {@inheritDoc}
     */
    public function supportsForeignKeyConstraints()
    {
        return false;
    }

741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
    /**
     * {@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.');
    }

765 766 767 768 769 770 771
    /**
     * {@inheritDoc}
     */
    public function getCreateConstraintSQL(Constraint $constraint, $table)
    {
        throw new DBALException('Sqlite platform does not support alter constraint.');
    }
772 773 774 775 776 777

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

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

783 784 785 786 787 788 789
    /**
     * {@inheritDoc}
     */
    public function getListTableForeignKeysSQL($table, $database = null)
    {
        $table = str_replace('.', '__', $table);

790
        return sprintf('PRAGMA foreign_key_list(%s)', $this->quoteStringLiteral($table));
791 792 793 794 795 796 797
    }

    /**
     * {@inheritDoc}
     */
    public function getAlterTableSQL(TableDiff $diff)
    {
798
        $sql = $this->getSimpleAlterTableSQL($diff);
799
        if ($sql !== false) {
800 801 802
            return $sql;
        }

803
        $fromTable = $diff->fromTable;
804
        if (! $fromTable instanceof Table) {
805 806 807 808 809
            throw new DBALException('Sqlite platform requires for alter table the table diff with reference to original table schema');
        }

        $table = clone $fromTable;

810
        $columns        = [];
811 812
        $oldColumnNames = [];
        $newColumnNames = [];
813
        $columnSql      = [];
814 815

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

821 822 823 824 825
        foreach ($diff->removedColumns as $columnName => $column) {
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
                continue;
            }

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

            unset(
                $columns[$columnName],
                $oldColumnNames[$columnName],
                $newColumnNames[$columnName]
            );
836 837 838 839 840 841 842
        }

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

843 844 845 846 847 848 849
            $oldColumnName = strtolower($oldColumnName);
            if (isset($columns[$oldColumnName])) {
                unset($columns[$oldColumnName]);
            }

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

850 851
            if (! isset($newColumnNames[$oldColumnName])) {
                continue;
852
            }
853 854

            $newColumnNames[$oldColumnName] = $column->getQuotedName($this);
855 856 857 858 859 860 861
        }

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

862 863
            if (isset($columns[$oldColumnName])) {
                unset($columns[$oldColumnName]);
864 865
            }

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

868 869
            if (! isset($newColumnNames[$oldColumnName])) {
                continue;
870
            }
871 872

            $newColumnNames[$oldColumnName] = $columnDiff->column->getQuotedName($this);
873 874
        }

875 876 877 878
        foreach ($diff->addedColumns as $columnName => $column) {
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
                continue;
            }
879

880
            $columns[strtolower($columnName)] = $column;
881 882
        }

883
        $sql      = [];
884
        $tableSql = [];
885

886 887
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
            $dataTable = new Table('__temp__' . $table->getName());
888

889
            $newTable = new Table($table->getQuotedName($this), $columns, $this->getPrimaryIndexInAlteredTable($diff), [], $this->getForeignKeysInAlteredTable($diff), $table->getOptions());
890
            $newTable->addOption('alter', true);
891

892 893 894
            $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));
895
            $sql[] = $this->getDropTableSQL($fromTable);
896

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

901
            if ($diff->newName && $diff->newName !== $diff->name) {
902
                $renamedTable = $diff->getNewName();
903
                $sql[]        = 'ALTER TABLE ' . $newTable->getQuotedName($this) . ' RENAME TO ' . $renamedTable->getQuotedName($this);
904 905
            }

906 907
            $sql = array_merge($sql, $this->getPostAlterTableIndexForeignKeySQL($diff));
        }
908 909 910 911

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

Benjamin Morel's avatar
Benjamin Morel committed
912
    /**
913
     * @return string[]|false
Benjamin Morel's avatar
Benjamin Morel committed
914
     */
915 916
    private function getSimpleAlterTableSQL(TableDiff $diff)
    {
917 918
        // Suppress changes on integer type autoincrement columns.
        foreach ($diff->changedColumns as $oldColumnName => $columnDiff) {
919
            if (! $columnDiff->fromColumn instanceof Column ||
920 921
                ! $columnDiff->column instanceof Column ||
                ! $columnDiff->column->getAutoincrement() ||
922
                ! $columnDiff->column->getType() instanceof Types\IntegerType
923 924 925 926
            ) {
                continue;
            }

927
            if (! $columnDiff->hasChanged('type') && $columnDiff->hasChanged('unsigned')) {
928 929 930 931 932
                unset($diff->changedColumns[$oldColumnName]);

                continue;
            }

933
            $fromColumnType = $columnDiff->fromColumn->getType();
934

935 936
            if (! ($fromColumnType instanceof Types\SmallIntType) && ! ($fromColumnType instanceof Types\BigIntType)) {
                continue;
937
            }
938 939

            unset($diff->changedColumns[$oldColumnName]);
940 941
        }

942
        if (! empty($diff->renamedColumns) || ! empty($diff->addedForeignKeys) || ! empty($diff->addedIndexes)
943 944
                || ! empty($diff->changedColumns) || ! empty($diff->changedForeignKeys) || ! empty($diff->changedIndexes)
                || ! empty($diff->removedColumns) || ! empty($diff->removedForeignKeys) || ! empty($diff->removedIndexes)
945
                || ! empty($diff->renamedIndexes)
946 947 948 949 950 951
        ) {
            return false;
        }

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

952 953
        $sql       = [];
        $tableSql  = [];
954
        $columnSql = [];
955

Benjamin Morel's avatar
Benjamin Morel committed
956
        foreach ($diff->addedColumns as $column) {
957 958 959 960
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
                continue;
            }

961
            $field = array_merge(['unique' => null, 'autoincrement' => null, 'default' => null], $column->toArray());
962
            $type  = $field['type'];
963 964
            switch (true) {
                case isset($field['columnDefinition']) || $field['autoincrement'] || $field['unique']:
965 966 967
                case $type instanceof Types\DateTimeType && $field['default'] === $this->getCurrentTimestampSQL():
                case $type instanceof Types\DateType && $field['default'] === $this->getCurrentDateSQL():
                case $type instanceof Types\TimeType && $field['default'] === $this->getCurrentTimeSQL():
968 969 970 971
                    return false;
            }

            $field['name'] = $column->getQuotedName($this);
972
            if ($type instanceof Types\StringType && $field['length'] === null) {
973 974 975
                $field['length'] = 255;
            }

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

979
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
980
            if ($diff->newName !== false) {
981
                $newTable = new Identifier($diff->newName);
982
                $sql[]    = 'ALTER TABLE ' . $table->getQuotedName($this) . ' RENAME TO ' . $newTable->getQuotedName($this);
983 984
            }
        }
985 986 987 988

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

Benjamin Morel's avatar
Benjamin Morel committed
989
    /**
990
     * @return string[]
Benjamin Morel's avatar
Benjamin Morel committed
991
     */
992
    private function getColumnNamesInAlteredTable(TableDiff $diff)
993
    {
994
        $columns = [];
995

996 997 998 999 1000 1001
        foreach ($diff->fromTable->getColumns() as $columnName => $column) {
            $columns[strtolower($columnName)] = $column->getName();
        }

        foreach ($diff->removedColumns as $columnName => $column) {
            $columnName = strtolower($columnName);
1002 1003
            if (! isset($columns[$columnName])) {
                continue;
1004
            }
1005 1006

            unset($columns[$columnName]);
1007 1008 1009
        }

        foreach ($diff->renamedColumns as $oldColumnName => $column) {
1010
            $columnName                          = $column->getName();
1011
            $columns[strtolower($oldColumnName)] = $columnName;
1012
            $columns[strtolower($columnName)]    = $columnName;
1013 1014 1015
        }

        foreach ($diff->changedColumns as $oldColumnName => $columnDiff) {
1016
            $columnName                          = $columnDiff->column->getName();
1017
            $columns[strtolower($oldColumnName)] = $columnName;
1018
            $columns[strtolower($columnName)]    = $columnName;
1019 1020 1021 1022 1023 1024 1025 1026 1027
        }

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

        return $columns;
    }

Benjamin Morel's avatar
Benjamin Morel committed
1028
    /**
1029
     * @return Index[]
Benjamin Morel's avatar
Benjamin Morel committed
1030
     */
1031 1032
    private function getIndexesInAlteredTable(TableDiff $diff)
    {
1033
        $indexes     = $diff->fromTable->getIndexes();
1034 1035 1036
        $columnNames = $this->getColumnNamesInAlteredTable($diff);

        foreach ($indexes as $key => $index) {
1037
            foreach ($diff->renamedIndexes as $oldIndexName => $renamedIndex) {
1038 1039
                if (strtolower($key) !== strtolower($oldIndexName)) {
                    continue;
1040
                }
1041 1042

                unset($indexes[$key]);
1043 1044
            }

1045
            $changed      = false;
1046
            $indexColumns = [];
1047 1048
            foreach ($index->getColumns() as $columnName) {
                $normalizedColumnName = strtolower($columnName);
1049
                if (! isset($columnNames[$normalizedColumnName])) {
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
                    unset($indexes[$key]);
                    continue 2;
                } else {
                    $indexColumns[] = $columnNames[$normalizedColumnName];
                    if ($columnName !== $columnNames[$normalizedColumnName]) {
                        $changed = true;
                    }
                }
            }

1060 1061
            if (! $changed) {
                continue;
1062
            }
1063 1064

            $indexes[$key] = new Index($index->getName(), $indexColumns, $index->isUnique(), $index->isPrimary(), $index->getFlags());
1065 1066 1067
        }

        foreach ($diff->removedIndexes as $index) {
1068
            $indexName = strtolower($index->getName());
1069 1070
            if (! strlen($indexName) || ! isset($indexes[$indexName])) {
                continue;
1071
            }
1072 1073

            unset($indexes[$indexName]);
1074 1075
        }

1076
        foreach (array_merge($diff->changedIndexes, $diff->addedIndexes, $diff->renamedIndexes) as $index) {
1077 1078 1079 1080 1081
            $indexName = strtolower($index->getName());
            if (strlen($indexName)) {
                $indexes[$indexName] = $index;
            } else {
                $indexes[] = $index;
1082 1083 1084
            }
        }

1085 1086 1087
        return $indexes;
    }

Benjamin Morel's avatar
Benjamin Morel committed
1088
    /**
1089
     * @return ForeignKeyConstraint[]
Benjamin Morel's avatar
Benjamin Morel committed
1090
     */
1091 1092 1093 1094 1095 1096
    private function getForeignKeysInAlteredTable(TableDiff $diff)
    {
        $foreignKeys = $diff->fromTable->getForeignKeys();
        $columnNames = $this->getColumnNamesInAlteredTable($diff);

        foreach ($foreignKeys as $key => $constraint) {
1097
            $changed      = false;
1098
            $localColumns = [];
1099 1100
            foreach ($constraint->getLocalColumns() as $columnName) {
                $normalizedColumnName = strtolower($columnName);
1101
                if (! isset($columnNames[$normalizedColumnName])) {
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
                    unset($foreignKeys[$key]);
                    continue 2;
                } else {
                    $localColumns[] = $columnNames[$normalizedColumnName];
                    if ($columnName !== $columnNames[$normalizedColumnName]) {
                        $changed = true;
                    }
                }
            }

1112 1113
            if (! $changed) {
                continue;
1114
            }
1115 1116

            $foreignKeys[$key] = new ForeignKeyConstraint($localColumns, $constraint->getForeignTableName(), $constraint->getForeignColumns(), $constraint->getName(), $constraint->getOptions());
1117 1118 1119 1120
        }

        foreach ($diff->removedForeignKeys as $constraint) {
            $constraintName = strtolower($constraint->getName());
1121 1122
            if (! strlen($constraintName) || ! isset($foreignKeys[$constraintName])) {
                continue;
1123
            }
1124 1125

            unset($foreignKeys[$constraintName]);
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
        }

        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
1140
    /**
1141
     * @return Index[]
Benjamin Morel's avatar
Benjamin Morel committed
1142
     */
1143 1144
    private function getPrimaryIndexInAlteredTable(TableDiff $diff)
    {
1145
        $primaryIndex = [];
1146 1147

        foreach ($this->getIndexesInAlteredTable($diff) as $index) {
1148 1149
            if (! $index->isPrimary()) {
                continue;
1150
            }
1151 1152

            $primaryIndex = [$index->getName() => $index];
1153 1154 1155 1156
        }

        return $primaryIndex;
    }
1157
}