Completed
Pull Request — develop (#3488)
by Sergei
17:41
created

SqlitePlatform::getIndexesInAlteredTable()   C

Complexity

Conditions 13
Paths 198

Size

Total Lines 55
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 31
CRAP Score 13.0051

Importance

Changes 0
Metric Value
eloc 33
dl 0
loc 55
ccs 31
cts 32
cp 0.9688
rs 5.8
c 0
b 0
f 0
cc 13
nc 198
nop 1
crap 13.0051

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
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
use Doctrine\DBAL\Schema\Index;
11
use Doctrine\DBAL\Schema\Table;
12
use Doctrine\DBAL\Schema\TableDiff;
13
use Doctrine\DBAL\TransactionIsolationLevel;
14
use Doctrine\DBAL\Types;
15
use function array_merge;
16
use function array_unique;
17
use function array_values;
18
use function implode;
19
use function is_numeric;
20
use function sprintf;
21
use function sqrt;
22
use function str_replace;
23
use function strlen;
24
use function strpos;
25
use function strtolower;
26
27
/**
28
 * The SqlitePlatform class describes the specifics and dialects of the SQLite
29
 * database platform.
30
 *
31
 * @todo   Rename: SQLitePlatform
32
 */
33
class SqlitePlatform extends AbstractPlatform
34
{
35
    /**
36
     * {@inheritDoc}
37
     */
38 1801
    public function getRegexpExpression()
39
    {
40 1801
        return 'REGEXP';
41
    }
42
43
    /**
44
     * {@inheritDoc}
45
     */
46
    public function getNowExpression($type = 'timestamp')
47
    {
48
        switch ($type) {
49
            case 'time':
50
                return 'time(\'now\')';
51
            case 'date':
52
                return 'date(\'now\')';
53
            case 'timestamp':
54
            default:
55
                return 'datetime(\'now\')';
56
        }
57
    }
58
59
    /**
60
     * {@inheritDoc}
61
     */
62 253
    public function getTrimExpression($str, $pos = TrimMode::UNSPECIFIED, $char = false)
63
    {
64 253
        $trimChar = $char !== false ? (', ' . $char) : '';
65
66 253
        switch ($pos) {
67
            case TrimMode::LEADING:
68 252
                $trimFn = 'LTRIM';
69 252
                break;
70
71
            case TrimMode::TRAILING:
72 251
                $trimFn = 'RTRIM';
73 251
                break;
74
75
            default:
76 253
                $trimFn = 'TRIM';
77
        }
78
79 253
        return $trimFn . '(' . $str . $trimChar . ')';
80
    }
81
82
    /**
83
     * {@inheritDoc}
84
     *
85
     * SQLite only supports the 2 parameter variant of this function
86
     */
87 1801
    public function getSubstringExpression($value, $position, $length = null)
88
    {
89 1801
        if ($length !== null) {
90 1801
            return 'SUBSTR(' . $value . ', ' . $position . ', ' . $length . ')';
91
        }
92
93 1801
        return 'SUBSTR(' . $value . ', ' . $position . ', LENGTH(' . $value . '))';
94
    }
95
96
    /**
97
     * {@inheritDoc}
98
     */
99 226
    public function getLocateExpression($str, $substr, $startPos = false)
100
    {
101 226
        if ($startPos === false) {
102 226
            return 'LOCATE(' . $str . ', ' . $substr . ')';
103
        }
104
105 226
        return 'LOCATE(' . $str . ', ' . $substr . ', ' . $startPos . ')';
106
    }
107
108
    /**
109
     * {@inheritdoc}
110
     */
111 1403
    protected function getDateArithmeticIntervalExpression($date, $operator, $interval, $unit)
112
    {
113 1403
        switch ($unit) {
114
            case DateIntervalUnit::SECOND:
115
            case DateIntervalUnit::MINUTE:
116
            case DateIntervalUnit::HOUR:
117 228
                return 'DATETIME(' . $date . ",'" . $operator . $interval . ' ' . $unit . "')";
118
119
            default:
120 1403
                switch ($unit) {
121
                    case DateIntervalUnit::WEEK:
122 228
                        $interval *= 7;
123 228
                        $unit      = DateIntervalUnit::DAY;
124 228
                        break;
125
126
                    case DateIntervalUnit::QUARTER:
127 228
                        $interval *= 3;
128 228
                        $unit      = DateIntervalUnit::MONTH;
129 228
                        break;
130
                }
131
132 1403
                if (! is_numeric($interval)) {
133 1378
                    $interval = "' || " . $interval . " || '";
134
                }
135
136 1403
                return 'DATE(' . $date . ",'" . $operator . $interval . ' ' . $unit . "')";
137
        }
138
    }
139
140
    /**
141
     * {@inheritDoc}
142
     */
143 201
    public function getDateDiffExpression($date1, $date2)
144
    {
145 201
        return sprintf("JULIANDAY(%s, 'start of day') - JULIANDAY(%s, 'start of day')", $date1, $date2);
146
    }
147
148
    /**
149
     * {@inheritDoc}
150
     */
151 1777
    protected function _getTransactionIsolationLevelSQL($level)
152
    {
153 1
        switch ($level) {
154 1776
            case TransactionIsolationLevel::READ_UNCOMMITTED:
155 1777
                return 0;
156 1776
            case TransactionIsolationLevel::READ_COMMITTED:
157 1776
            case TransactionIsolationLevel::REPEATABLE_READ:
158 1776
            case TransactionIsolationLevel::SERIALIZABLE:
159 1777
                return 1;
160
            default:
161
                return parent::_getTransactionIsolationLevelSQL($level);
162
        }
163
    }
164
165
    /**
166
     * {@inheritDoc}
167
     */
168 1777
    public function getSetTransactionIsolationSQL($level)
169
    {
170 1777
        return 'PRAGMA read_uncommitted = ' . $this->_getTransactionIsolationLevelSQL($level);
171
    }
172
173
    /**
174
     * {@inheritDoc}
175
     */
176 1762
    public function prefersIdentityColumns()
177
    {
178 1762
        return true;
179
    }
180
181
    /**
182
     * {@inheritDoc}
183
     */
184 965
    public function getBooleanTypeDeclarationSQL(array $field)
185
    {
186 965
        return 'BOOLEAN';
187
    }
188
189
    /**
190
     * {@inheritDoc}
191
     */
192 1941
    public function getIntegerTypeDeclarationSQL(array $field)
193
    {
194 1941
        return 'INTEGER' . $this->_getCommonIntegerTypeDeclarationSQL($field);
195
    }
196
197
    /**
198
     * {@inheritDoc}
199
     */
200 1733
    public function getBigIntTypeDeclarationSQL(array $field)
201
    {
202
        //  SQLite autoincrement is implicit for INTEGER PKs, but not for BIGINT fields.
203 1733
        if (! empty($field['autoincrement'])) {
204 1733
            return $this->getIntegerTypeDeclarationSQL($field);
205
        }
206
207 1673
        return 'BIGINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
208
    }
209
210
    /**
211
     * {@inheritDoc}
212
     */
213 1706
    public function getTinyIntTypeDeclarationSql(array $field)
214
    {
215
        //  SQLite autoincrement is implicit for INTEGER PKs, but not for TINYINT fields.
216 1706
        if (! empty($field['autoincrement'])) {
217 1706
            return $this->getIntegerTypeDeclarationSQL($field);
218
        }
219
220 1705
        return 'TINYINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
221
    }
222
223
    /**
224
     * {@inheritDoc}
225
     */
226 1783
    public function getSmallIntTypeDeclarationSQL(array $field)
227
    {
228
        //  SQLite autoincrement is implicit for INTEGER PKs, but not for SMALLINT fields.
229 1783
        if (! empty($field['autoincrement'])) {
230 1783
            return $this->getIntegerTypeDeclarationSQL($field);
231
        }
232
233 1760
        return 'SMALLINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
234
    }
235
236
    /**
237
     * {@inheritDoc}
238
     */
239 1657
    public function getMediumIntTypeDeclarationSql(array $field)
240
    {
241
        //  SQLite autoincrement is implicit for INTEGER PKs, but not for MEDIUMINT fields.
242 1657
        if (! empty($field['autoincrement'])) {
243 1657
            return $this->getIntegerTypeDeclarationSQL($field);
244
        }
245
246 1657
        return 'MEDIUMINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
247
    }
248
249
    /**
250
     * {@inheritDoc}
251
     */
252 254
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
253
    {
254 254
        return 'DATETIME';
255
    }
256
257
    /**
258
     * {@inheritDoc}
259
     */
260 227
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
261
    {
262 227
        return 'DATE';
263
    }
264
265
    /**
266
     * {@inheritDoc}
267
     */
268 164
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
269
    {
270 164
        return 'TIME';
271
    }
272
273
    /**
274
     * {@inheritDoc}
275
     */
276 1941
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
277
    {
278
        // sqlite autoincrement is only possible for the primary key
279 1941
        if (! empty($columnDef['autoincrement'])) {
280 1881
            return ' PRIMARY KEY AUTOINCREMENT';
281
        }
282
283 1915
        return ! empty($columnDef['unsigned']) ? ' UNSIGNED' : '';
284
    }
285
286
    /**
287
     * {@inheritDoc}
288
     */
289 1495
    public function getForeignKeyDeclarationSQL(ForeignKeyConstraint $foreignKey)
290
    {
291 1495
        return parent::getForeignKeyDeclarationSQL(new ForeignKeyConstraint(
292 1495
            $foreignKey->getQuotedLocalColumns($this),
293 1495
            str_replace('.', '__', $foreignKey->getQuotedForeignTableName($this)),
294 1495
            $foreignKey->getQuotedForeignColumns($this),
295 1495
            $foreignKey->getName(),
296 1495
            $foreignKey->getOptions()
297
        ));
298
    }
299
300
    /**
301
     * {@inheritDoc}
302
     */
303 1714
    protected function _getCreateTableSQL($tableName, array $columns, array $options = [])
304
    {
305 1714
        $tableName   = str_replace('.', '__', $tableName);
306 1714
        $queryFields = $this->getColumnDeclarationListSQL($columns);
307
308 1714
        if (isset($options['uniqueConstraints']) && ! empty($options['uniqueConstraints'])) {
309
            foreach ($options['uniqueConstraints'] as $name => $definition) {
310
                $queryFields .= ', ' . $this->getUniqueConstraintDeclarationSQL($name, $definition);
311
            }
312
        }
313
314 1714
        $queryFields .= $this->getNonAutoincrementPrimaryKeyDefinition($columns, $options);
315
316 1714
        if (isset($options['foreignKeys'])) {
317 1713
            foreach ($options['foreignKeys'] as $foreignKey) {
318 1495
                $queryFields .= ', ' . $this->getForeignKeyDeclarationSQL($foreignKey);
319
            }
320
        }
321
322 1714
        $query = ['CREATE TABLE ' . $tableName . ' (' . $queryFields . ')'];
323
324 1714
        if (isset($options['alter']) && $options['alter'] === true) {
325 1479
            return $query;
326
        }
327
328 1702
        if (isset($options['indexes']) && ! empty($options['indexes'])) {
329 1558
            foreach ($options['indexes'] as $indexDef) {
330 1558
                $query[] = $this->getCreateIndexSQL($indexDef, $tableName);
331
            }
332
        }
333
334 1702
        if (isset($options['unique']) && ! empty($options['unique'])) {
335
            foreach ($options['unique'] as $indexDef) {
336
                $query[] = $this->getCreateIndexSQL($indexDef, $tableName);
337
            }
338
        }
339
340 1702
        return $query;
341
    }
342
343
    /**
344
     * Generate a PRIMARY KEY definition if no autoincrement value is used
345
     *
346
     * @param mixed[][] $columns
347
     * @param mixed[]   $options
348
     */
349 1714
    private function getNonAutoincrementPrimaryKeyDefinition(array $columns, array $options) : string
350
    {
351 1714
        if (empty($options['primary'])) {
352 1317
            return '';
353
        }
354
355 1700
        $keyColumns = array_unique(array_values($options['primary']));
356
357 1700
        foreach ($keyColumns as $keyColumn) {
358 1700
            if (! empty($columns[$keyColumn]['autoincrement'])) {
359 1654
                return '';
360
            }
361
        }
362
363 1605
        return ', PRIMARY KEY(' . implode(', ', $keyColumns) . ')';
364
    }
365
366
    /**
367
     * {@inheritDoc}
368
     */
369 1811
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
370
    {
371 1811
        return $fixed
372 1743
            ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)')
373 1811
            : ($length ? 'VARCHAR(' . $length . ')' : 'TEXT');
374
    }
375
376
    /**
377
     * {@inheritdoc}
378
     */
379 1464
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
380
    {
381 1464
        return 'BLOB';
382
    }
383
384
    /**
385
     * {@inheritdoc}
386
     */
387 505
    public function getBinaryMaxLength()
388
    {
389 505
        return 0;
390
    }
391
392
    /**
393
     * {@inheritdoc}
394
     */
395 1465
    public function getBinaryDefaultLength()
396
    {
397 1465
        return 0;
398
    }
399
400
    /**
401
     * {@inheritDoc}
402
     */
403 746
    public function getClobTypeDeclarationSQL(array $field)
404
    {
405 746
        return 'CLOB';
406
    }
407
408
    /**
409
     * {@inheritDoc}
410
     */
411 1297
    public function getListTableConstraintsSQL($table)
412
    {
413 1297
        $table = str_replace('.', '__', $table);
414
415 1297
        return sprintf(
416 1
            "SELECT sql FROM sqlite_master WHERE type='index' AND tbl_name = %s AND sql NOT NULL ORDER BY name",
417 1297
            $this->quoteStringLiteral($table)
418
        );
419
    }
420
421
    /**
422
     * {@inheritDoc}
423
     */
424 1405
    public function getListTableColumnsSQL($table, $currentDatabase = null)
425
    {
426 1405
        $table = str_replace('.', '__', $table);
427
428 1405
        return sprintf('PRAGMA table_info(%s)', $this->quoteStringLiteral($table));
429
    }
430
431
    /**
432
     * {@inheritDoc}
433
     */
434 1382
    public function getListTableIndexesSQL($table, $currentDatabase = null)
435
    {
436 1382
        $table = str_replace('.', '__', $table);
437
438 1382
        return sprintf('PRAGMA index_list(%s)', $this->quoteStringLiteral($table));
439
    }
440
441
    /**
442
     * {@inheritDoc}
443
     */
444 304
    public function getListTablesSQL()
445
    {
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 304
             . "WHERE type = 'table' ORDER BY name";
449
    }
450
451
    /**
452
     * {@inheritDoc}
453
     */
454 155
    public function getListViewsSQL($database)
455
    {
456 155
        return "SELECT name, sql FROM sqlite_master WHERE type='view' AND sql NOT NULL";
457
    }
458
459
    /**
460
     * {@inheritDoc}
461
     */
462 155
    public function getCreateViewSQL($name, $sql)
463
    {
464 155
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
465
    }
466
467
    /**
468
     * {@inheritDoc}
469
     */
470 155
    public function getDropViewSQL($name)
471
    {
472 155
        return 'DROP VIEW ' . $name;
473
    }
474
475
    /**
476
     * {@inheritDoc}
477
     */
478 1495
    public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey)
479
    {
480 1495
        $query = parent::getAdvancedForeignKeyOptionsSQL($foreignKey);
481
482 1495
        $query .= ($foreignKey->hasOption('deferrable') && $foreignKey->getOption('deferrable') !== false ? ' ' : ' NOT ') . 'DEFERRABLE';
483 1495
        $query .= ' INITIALLY ' . ($foreignKey->hasOption('deferred') && $foreignKey->getOption('deferred') !== false ? 'DEFERRED' : 'IMMEDIATE');
484
485 1495
        return $query;
486
    }
487
488
    /**
489
     * {@inheritDoc}
490
     */
491 154
    public function supportsIdentityColumns()
492
    {
493 154
        return true;
494
    }
495
496
    /**
497
     * {@inheritDoc}
498
     */
499 1306
    public function supportsColumnCollation()
500
    {
501 1306
        return true;
502
    }
503
504
    /**
505
     * {@inheritDoc}
506
     */
507 1718
    public function supportsInlineColumnComments()
508
    {
509 1718
        return true;
510
    }
511
512
    /**
513
     * {@inheritDoc}
514
     */
515 2014
    public function getName()
516
    {
517 2014
        return 'sqlite';
518
    }
519
520
    /**
521
     * {@inheritDoc}
522
     */
523 792
    public function getTruncateTableSQL($tableName, $cascade = false)
524
    {
525 792
        $tableIdentifier = new Identifier($tableName);
526 792
        $tableName       = str_replace('.', '__', $tableIdentifier->getQuotedName($this));
527
528 792
        return 'DELETE FROM ' . $tableName;
529
    }
530
531
    /**
532
     * User-defined function for Sqlite that is used with PDO::sqliteCreateFunction().
533
     *
534
     * @param int|float $value
535
     *
536
     * @return float
537
     */
538
    public static function udfSqrt($value)
539
    {
540
        return sqrt($value);
541
    }
542
543
    /**
544
     * User-defined function for Sqlite that implements MOD(a, b).
545
     *
546
     * @param int $a
547
     * @param int $b
548
     *
549
     * @return int
550
     */
551
    public static function udfMod($a, $b)
552
    {
553
        return $a % $b;
554
    }
555
556
    /**
557
     * @param string $str
558
     * @param string $substr
559
     * @param int    $offset
560
     *
561
     * @return int
562
     */
563 226
    public static function udfLocate($str, $substr, $offset = 0)
564
    {
565
        // SQL's LOCATE function works on 1-based positions, while PHP's strpos works on 0-based positions.
566
        // So we have to make them compatible if an offset is given.
567 226
        if ($offset > 0) {
568 226
            $offset -= 1;
569
        }
570
571 226
        $pos = strpos($str, $substr, $offset);
572
573 226
        if ($pos !== false) {
574 226
            return $pos + 1;
575
        }
576
577 226
        return 0;
578
    }
579
580
    /**
581
     * {@inheritDoc}
582
     */
583
    public function getForUpdateSql()
584
    {
585
        return '';
586
    }
587
588
    /**
589
     * {@inheritDoc}
590
     */
591 572
    public function getInlineColumnCommentSQL($comment)
592
    {
593 572
        return '--' . str_replace("\n", "\n--", $comment) . "\n";
594
    }
595
596
    /**
597
     * {@inheritDoc}
598
     */
599 1201
    protected function initializeDoctrineTypeMappings()
600
    {
601 1201
        $this->doctrineTypeMapping = [
602
            'bigint'           => 'bigint',
603
            'bigserial'        => 'bigint',
604
            'blob'             => 'blob',
605
            'boolean'          => 'boolean',
606
            'char'             => 'string',
607
            'clob'             => 'text',
608
            'date'             => 'date',
609
            'datetime'         => 'datetime',
610
            'decimal'          => 'decimal',
611
            'double'           => 'float',
612
            'double precision' => 'float',
613
            'float'            => 'float',
614
            'image'            => 'string',
615
            'int'              => 'integer',
616
            'integer'          => 'integer',
617
            'longtext'         => 'text',
618
            'longvarchar'      => 'string',
619
            'mediumint'        => 'integer',
620
            'mediumtext'       => 'text',
621
            'ntext'            => 'string',
622
            'numeric'          => 'decimal',
623
            'nvarchar'         => 'string',
624
            'real'             => 'float',
625
            'serial'           => 'integer',
626
            'smallint'         => 'smallint',
627
            'string'           => 'string',
628
            'text'             => 'text',
629
            'time'             => 'time',
630
            'timestamp'        => 'datetime',
631
            'tinyint'          => 'boolean',
632
            'tinytext'         => 'text',
633
            'varchar'          => 'string',
634
            'varchar2'         => 'string',
635
        ];
636 1201
    }
637
638
    /**
639
     * {@inheritDoc}
640
     */
641 1728
    protected function getReservedKeywordsClass()
642
    {
643 1728
        return Keywords\SQLiteKeywords::class;
644
    }
645
646
    /**
647
     * {@inheritDoc}
648
     */
649 1479
    protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff)
650
    {
651 1479
        if (! $diff->fromTable instanceof Table) {
652
            throw new DBALException('Sqlite platform requires for alter table the table diff with reference to original table schema');
653
        }
654
655 1479
        $sql = [];
656 1479
        foreach ($diff->fromTable->getIndexes() as $index) {
657 1473
            if ($index->isPrimary()) {
658 1471
                continue;
659
            }
660
661 1470
            $sql[] = $this->getDropIndexSQL($index, $diff->name);
662
        }
663
664 1479
        return $sql;
665
    }
666
667
    /**
668
     * {@inheritDoc}
669
     */
670 1479
    protected function getPostAlterTableIndexForeignKeySQL(TableDiff $diff)
671
    {
672 1479
        if (! $diff->fromTable instanceof Table) {
673
            throw new DBALException('Sqlite platform requires for alter table the table diff with reference to original table schema');
674
        }
675
676 1479
        $sql       = [];
677 1479
        $tableName = $diff->getNewName();
678
679 1479
        if ($tableName === false) {
680 901
            $tableName = $diff->getName($this);
681
        }
682
683 1479
        foreach ($this->getIndexesInAlteredTable($diff) as $index) {
684 1473
            if ($index->isPrimary()) {
685 1471
                continue;
686
            }
687
688 1472
            $sql[] = $this->getCreateIndexSQL($index, $tableName->getQuotedName($this));
689
        }
690
691 1479
        return $sql;
692
    }
693
694
    /**
695
     * {@inheritDoc}
696
     */
697 1692
    protected function doModifyLimitQuery(string $query, ?int $limit, int $offset) : string
698
    {
699 1692
        if ($limit === null && $offset > 0) {
700 1666
            $limit = -1;
701
        }
702
703 1692
        return parent::doModifyLimitQuery($query, $limit, $offset);
704
    }
705
706
    /**
707
     * {@inheritDoc}
708
     */
709 262
    public function getBlobTypeDeclarationSQL(array $field)
710
    {
711 262
        return 'BLOB';
712
    }
713
714
    /**
715
     * {@inheritDoc}
716
     */
717 111
    public function getTemporaryTableName($tableName)
718
    {
719 111
        $tableName = str_replace('.', '__', $tableName);
720
721 111
        return $tableName;
722
    }
723
724
    /**
725
     * {@inheritDoc}
726
     *
727
     * Sqlite Platform emulates schema by underscoring each dot and generating tables
728
     * into the default database.
729
     *
730
     * This hack is implemented to be able to use SQLite as testdriver when
731
     * using schema supporting databases.
732
     */
733
    public function canEmulateSchemas()
734
    {
735
        return true;
736
    }
737
738
    /**
739
     * {@inheritDoc}
740
     */
741 1566
    public function supportsForeignKeyConstraints()
742
    {
743 1566
        return false;
744
    }
745
746
    /**
747
     * {@inheritDoc}
748
     */
749
    public function getCreatePrimaryKeySQL(Index $index, $table)
750
    {
751
        throw new DBALException('Sqlite platform does not support alter primary key.');
752
    }
753
754
    /**
755
     * {@inheritdoc}
756
     */
757 1586
    public function getCreateForeignKeySQL(ForeignKeyConstraint $foreignKey, $table)
758
    {
759 1586
        throw new DBALException('Sqlite platform does not support alter foreign key.');
760
    }
761
762
    /**
763
     * {@inheritdoc}
764
     */
765
    public function getDropForeignKeySQL($foreignKey, $table)
766
    {
767
        throw new DBALException('Sqlite platform does not support alter foreign key.');
768
    }
769
770
    /**
771
     * {@inheritDoc}
772
     */
773 1561
    public function getCreateConstraintSQL(Constraint $constraint, $table)
774
    {
775 1561
        throw new DBALException('Sqlite platform does not support alter constraint.');
776
    }
777
778
    /**
779
     * {@inheritDoc}
780
     */
781 1715
    public function getCreateTableSQL(Table $table, $createFlags = null)
782
    {
783 1715
        $createFlags = $createFlags ?? self::CREATE_INDEXES | self::CREATE_FOREIGNKEYS;
784
785 1715
        return parent::getCreateTableSQL($table, $createFlags);
786
    }
787
788
    /**
789
     * {@inheritDoc}
790
     */
791 1374
    public function getListTableForeignKeysSQL($table, $database = null)
0 ignored issues
show
Unused Code introduced by
The parameter $database is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

791
    public function getListTableForeignKeysSQL($table, /** @scrutinizer ignore-unused */ $database = null)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
792
    {
793 1374
        $table = str_replace('.', '__', $table);
794
795 1374
        return sprintf('PRAGMA foreign_key_list(%s)', $this->quoteStringLiteral($table));
796
    }
797
798
    /**
799
     * {@inheritDoc}
800
     */
801 1596
    public function getAlterTableSQL(TableDiff $diff)
802
    {
803 1596
        $sql = $this->getSimpleAlterTableSQL($diff);
804 1596
        if ($sql !== false) {
0 ignored issues
show
introduced by
The condition $sql !== false is always false.
Loading history...
805 1582
            return $sql;
806
        }
807
808 1550
        $fromTable = $diff->fromTable;
809 1550
        if (! $fromTable instanceof Table) {
810 1442
            throw new DBALException('Sqlite platform requires for alter table the table diff with reference to original table schema');
811
        }
812
813 1479
        $table = clone $fromTable;
814
815 1479
        $columns        = [];
816 1479
        $oldColumnNames = [];
817 1479
        $newColumnNames = [];
818 1479
        $columnSql      = [];
819
820 1479
        foreach ($table->getColumns() as $columnName => $column) {
821 1478
            $columnName                  = strtolower($columnName);
822 1478
            $columns[$columnName]        = $column;
823 1478
            $oldColumnNames[$columnName] = $newColumnNames[$columnName] = $column->getQuotedName($this);
824
        }
825
826 1479
        foreach ($diff->removedColumns as $columnName => $column) {
827 1471
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
828
                continue;
829
            }
830
831 1471
            $columnName = strtolower($columnName);
832 1471
            if (! isset($columns[$columnName])) {
833
                continue;
834
            }
835
836
            unset(
837 1471
                $columns[$columnName],
838 1471
                $oldColumnNames[$columnName],
839 1471
                $newColumnNames[$columnName]
840
            );
841
        }
842
843 1479
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
844 1373
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
845
                continue;
846
            }
847
848 1373
            $oldColumnName = strtolower($oldColumnName);
849 1373
            if (isset($columns[$oldColumnName])) {
850 1373
                unset($columns[$oldColumnName]);
851
            }
852
853 1373
            $columns[strtolower($column->getName())] = $column;
854
855 1373
            if (! isset($newColumnNames[$oldColumnName])) {
856
                continue;
857
            }
858
859 1373
            $newColumnNames[$oldColumnName] = $column->getQuotedName($this);
860
        }
861
862 1479
        foreach ($diff->changedColumns as $oldColumnName => $columnDiff) {
863 940
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
864
                continue;
865
            }
866
867 940
            if (isset($columns[$oldColumnName])) {
868 939
                unset($columns[$oldColumnName]);
869
            }
870
871 940
            $columns[strtolower($columnDiff->column->getName())] = $columnDiff->column;
872
873 940
            if (! isset($newColumnNames[$oldColumnName])) {
874 553
                continue;
875
            }
876
877 939
            $newColumnNames[$oldColumnName] = $columnDiff->column->getQuotedName($this);
878
        }
879
880 1479
        foreach ($diff->addedColumns as $columnName => $column) {
881 941
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
882
                continue;
883
            }
884
885 941
            $columns[strtolower($columnName)] = $column;
886
        }
887
888 1479
        $sql      = [];
889 1479
        $tableSql = [];
890
891 1479
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
892 1479
            $dataTable = new Table('__temp__' . $table->getName());
893
894 1479
            $newTable = new Table($table->getQuotedName($this), $columns, $this->getPrimaryIndexInAlteredTable($diff), [], $this->getForeignKeysInAlteredTable($diff), $table->getOptions());
895 1479
            $newTable->addOption('alter', true);
896
897 1479
            $sql = $this->getPreAlterTableIndexForeignKeySQL($diff);
898
            //$sql = array_merge($sql, $this->getCreateTableSQL($dataTable, 0));
899 1479
            $sql[] = sprintf('CREATE TEMPORARY TABLE %s AS SELECT %s FROM %s', $dataTable->getQuotedName($this), implode(', ', $oldColumnNames), $table->getQuotedName($this));
900 1479
            $sql[] = $this->getDropTableSQL($fromTable);
901
902 1479
            $sql   = array_merge($sql, $this->getCreateTableSQL($newTable));
903 1479
            $sql[] = sprintf('INSERT INTO %s (%s) SELECT %s FROM %s', $newTable->getQuotedName($this), implode(', ', $newColumnNames), implode(', ', $oldColumnNames), $dataTable->getQuotedName($this));
904 1479
            $sql[] = $this->getDropTableSQL($dataTable);
905
906 1479
            $newName = $diff->getNewName();
907
908 1479
            if ($newName !== false) {
909 1371
                $sql[] = sprintf(
910 3
                    'ALTER TABLE %s RENAME TO %s',
911 1371
                    $newTable->getQuotedName($this),
912 1371
                    $newName->getQuotedName($this)
913
                );
914
            }
915
916 1479
            $sql = array_merge($sql, $this->getPostAlterTableIndexForeignKeySQL($diff));
917
        }
918
919 1479
        return array_merge($sql, $tableSql, $columnSql);
920
    }
921
922
    /**
923
     * @return string[]|false
924
     */
925 1596
    private function getSimpleAlterTableSQL(TableDiff $diff)
926
    {
927
        // Suppress changes on integer type autoincrement columns.
928 1596
        foreach ($diff->changedColumns as $oldColumnName => $columnDiff) {
929 960
            if (! $columnDiff->fromColumn instanceof Column ||
930 956
                ! $columnDiff->column instanceof Column ||
931 956
                ! $columnDiff->column->getAutoincrement() ||
932 960
                ! $columnDiff->column->getType() instanceof Types\IntegerType
933
            ) {
934 940
                continue;
935
            }
936
937 172
            if (! $columnDiff->hasChanged('type') && $columnDiff->hasChanged('unsigned')) {
938 169
                unset($diff->changedColumns[$oldColumnName]);
939
940 169
                continue;
941
            }
942
943 172
            $fromColumnType = $columnDiff->fromColumn->getType();
944
945 172
            if (! ($fromColumnType instanceof Types\SmallIntType) && ! ($fromColumnType instanceof Types\BigIntType)) {
946
                continue;
947
            }
948
949 172
            unset($diff->changedColumns[$oldColumnName]);
950
        }
951
952 1596
        if (! empty($diff->renamedColumns) || ! empty($diff->addedForeignKeys) || ! empty($diff->addedIndexes)
953 1591
                || ! empty($diff->changedColumns) || ! empty($diff->changedForeignKeys) || ! empty($diff->changedIndexes)
954 1587
                || ! empty($diff->removedColumns) || ! empty($diff->removedForeignKeys) || ! empty($diff->removedIndexes)
955 1596
                || ! empty($diff->renamedIndexes)
956
        ) {
957 1479
            return false;
958
        }
959
960 1584
        $table = new Table($diff->name);
961
962 1584
        $sql       = [];
963 1584
        $tableSql  = [];
964 1584
        $columnSql = [];
965
966 1584
        foreach ($diff->addedColumns as $column) {
967 1467
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
968
                continue;
969
            }
970
971 1467
            $field = array_merge(['unique' => null, 'autoincrement' => null, 'default' => null], $column->toArray());
972 1467
            $type  = $field['type'];
973
            switch (true) {
974 1467
                case isset($field['columnDefinition']) || $field['autoincrement'] || $field['unique']:
975 1466
                case $type instanceof Types\DateTimeType && $field['default'] === $this->getCurrentTimestampSQL():
976 1466
                case $type instanceof Types\DateType && $field['default'] === $this->getCurrentDateSQL():
977 1465
                case $type instanceof Types\TimeType && $field['default'] === $this->getCurrentTimeSQL():
978 1442
                    return false;
979
            }
980
981 1465
            $field['name'] = $column->getQuotedName($this);
982 1465
            if ($type instanceof Types\StringType && $field['length'] === null) {
983 1465
                $field['length'] = 255;
984
            }
985
986 1465
            $sql[] = 'ALTER TABLE ' . $table->getQuotedName($this) . ' ADD COLUMN ' . $this->getColumnDeclarationSQL($field['name'], $field);
987
        }
988
989 1582
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
990 1582
            if ($diff->newName !== false) {
991 178
                $newTable = new Identifier($diff->newName);
0 ignored issues
show
Bug introduced by
It seems like $diff->newName can also be of type true; however, parameter $identifier of Doctrine\DBAL\Schema\Identifier::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

991
                $newTable = new Identifier(/** @scrutinizer ignore-type */ $diff->newName);
Loading history...
992 178
                $sql[]    = 'ALTER TABLE ' . $table->getQuotedName($this) . ' RENAME TO ' . $newTable->getQuotedName($this);
993
            }
994
        }
995
996 1582
        return array_merge($sql, $tableSql, $columnSql);
997
    }
998
999
    /**
1000
     * @return string[]
1001
     */
1002 1479
    private function getColumnNamesInAlteredTable(TableDiff $diff)
1003
    {
1004 1479
        $columns = [];
1005
1006 1479
        foreach ($diff->fromTable->getColumns() as $columnName => $column) {
0 ignored issues
show
Bug introduced by
The method getColumns() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1006
        foreach ($diff->fromTable->/** @scrutinizer ignore-call */ getColumns() as $columnName => $column) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
1007 1478
            $columns[strtolower($columnName)] = $column->getName();
1008
        }
1009
1010 1479
        foreach ($diff->removedColumns as $columnName => $column) {
1011 1471
            $columnName = strtolower($columnName);
1012 1471
            if (! isset($columns[$columnName])) {
1013
                continue;
1014
            }
1015
1016 1471
            unset($columns[$columnName]);
1017
        }
1018
1019 1479
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
1020 1373
            $columnName                          = $column->getName();
1021 1373
            $columns[strtolower($oldColumnName)] = $columnName;
1022 1373
            $columns[strtolower($columnName)]    = $columnName;
1023
        }
1024
1025 1479
        foreach ($diff->changedColumns as $oldColumnName => $columnDiff) {
1026 940
            $columnName                          = $columnDiff->column->getName();
1027 940
            $columns[strtolower($oldColumnName)] = $columnName;
1028 940
            $columns[strtolower($columnName)]    = $columnName;
1029
        }
1030
1031 1479
        foreach ($diff->addedColumns as $column) {
1032 941
            $columnName                       = $column->getName();
1033 941
            $columns[strtolower($columnName)] = $columnName;
1034
        }
1035
1036 1479
        return $columns;
1037
    }
1038
1039
    /**
1040
     * @return Index[]
1041
     */
1042 1479
    private function getIndexesInAlteredTable(TableDiff $diff)
1043
    {
1044 1479
        $indexes     = $diff->fromTable->getIndexes();
1045 1479
        $columnNames = $this->getColumnNamesInAlteredTable($diff);
1046
1047 1479
        foreach ($indexes as $key => $index) {
1048 1473
            foreach ($diff->renamedIndexes as $oldIndexName => $renamedIndex) {
1049 619
                if (strtolower($key) !== strtolower($oldIndexName)) {
1050 619
                    continue;
1051
                }
1052
1053 341
                unset($indexes[$key]);
1054
            }
1055
1056 1473
            $changed      = false;
1057 1473
            $indexColumns = [];
1058 1473
            foreach ($index->getColumns() as $columnName) {
1059 1473
                $normalizedColumnName = strtolower($columnName);
1060 1473
                if (! isset($columnNames[$normalizedColumnName])) {
1061 1369
                    unset($indexes[$key]);
1062 1369
                    continue 2;
1063
                } else {
1064 1473
                    $indexColumns[] = $columnNames[$normalizedColumnName];
1065 1473
                    if ($columnName !== $columnNames[$normalizedColumnName]) {
1066 1374
                        $changed = true;
1067
                    }
1068
                }
1069
            }
1070
1071 1473
            if (! $changed) {
1072 1473
                continue;
1073
            }
1074
1075 1369
            $indexes[$key] = new Index($index->getName(), $indexColumns, $index->isUnique(), $index->isPrimary(), $index->getFlags());
1076
        }
1077
1078 1479
        foreach ($diff->removedIndexes as $index) {
1079 1468
            $indexName = strtolower($index->getName());
1080 1468
            if (! strlen($indexName) || ! isset($indexes[$indexName])) {
1081
                continue;
1082
            }
1083
1084 1468
            unset($indexes[$indexName]);
1085
        }
1086
1087 1479
        foreach (array_merge($diff->changedIndexes, $diff->addedIndexes, $diff->renamedIndexes) as $index) {
1088 619
            $indexName = strtolower($index->getName());
1089 619
            if (strlen($indexName)) {
1090 619
                $indexes[$indexName] = $index;
1091
            } else {
1092 3
                $indexes[] = $index;
1093
            }
1094
        }
1095
1096 1479
        return $indexes;
1097
    }
1098
1099
    /**
1100
     * @return ForeignKeyConstraint[]
1101
     */
1102 1479
    private function getForeignKeysInAlteredTable(TableDiff $diff)
1103
    {
1104 1479
        $foreignKeys = $diff->fromTable->getForeignKeys();
1105 1479
        $columnNames = $this->getColumnNamesInAlteredTable($diff);
1106
1107 1479
        foreach ($foreignKeys as $key => $constraint) {
1108 1371
            $changed      = false;
1109 1371
            $localColumns = [];
1110 1371
            foreach ($constraint->getLocalColumns() as $columnName) {
1111 1371
                $normalizedColumnName = strtolower($columnName);
1112 1371
                if (! isset($columnNames[$normalizedColumnName])) {
1113 1369
                    unset($foreignKeys[$key]);
1114 1369
                    continue 2;
1115
                } else {
1116 1371
                    $localColumns[] = $columnNames[$normalizedColumnName];
1117 1371
                    if ($columnName !== $columnNames[$normalizedColumnName]) {
1118 1371
                        $changed = true;
1119
                    }
1120
                }
1121
            }
1122
1123 1371
            if (! $changed) {
1124 1371
                continue;
1125
            }
1126
1127 1369
            $foreignKeys[$key] = new ForeignKeyConstraint($localColumns, $constraint->getForeignTableName(), $constraint->getForeignColumns(), $constraint->getName(), $constraint->getOptions());
1128
        }
1129
1130 1479
        foreach ($diff->removedForeignKeys as $constraint) {
1131 241
            if (! $constraint instanceof ForeignKeyConstraint) {
1132
                $constraint = new Identifier($constraint);
1133
            }
1134
1135 241
            $constraintName = strtolower($constraint->getName());
1136 241
            if (! strlen($constraintName) || ! isset($foreignKeys[$constraintName])) {
1137
                continue;
1138
            }
1139
1140 241
            unset($foreignKeys[$constraintName]);
1141
        }
1142
1143 1479
        foreach (array_merge($diff->changedForeignKeys, $diff->addedForeignKeys) as $constraint) {
1144 387
            $constraintName = strtolower($constraint->getName());
1145 387
            if (strlen($constraintName)) {
1146 241
                $foreignKeys[$constraintName] = $constraint;
1147
            } else {
1148 157
                $foreignKeys[] = $constraint;
1149
            }
1150
        }
1151
1152 1479
        return $foreignKeys;
1153
    }
1154
1155
    /**
1156
     * @return Index[]
1157
     */
1158 1479
    private function getPrimaryIndexInAlteredTable(TableDiff $diff)
1159
    {
1160 1479
        $primaryIndex = [];
1161
1162 1479
        foreach ($this->getIndexesInAlteredTable($diff) as $index) {
1163 1473
            if (! $index->isPrimary()) {
1164 1472
                continue;
1165
            }
1166
1167 1471
            $primaryIndex = [$index->getName() => $index];
1168
        }
1169
1170 1479
        return $primaryIndex;
1171
    }
1172
}
1173