Failed Conditions
Pull Request — develop (#3348)
by Sergei
65:23
created

SqlitePlatform::getForeignKeysInAlteredTable()   B

Complexity

Conditions 11
Paths 120

Size

Total Lines 55
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 28
CRAP Score 11.0359

Importance

Changes 0
Metric Value
eloc 31
dl 0
loc 55
ccs 28
cts 30
cp 0.9333
rs 7.15
c 0
b 0
f 0
cc 11
nc 120
nop 1
crap 11.0359

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
declare(strict_types=1);
4
5
namespace Doctrine\DBAL\Platforms;
6
7
use Doctrine\DBAL\DBALException;
8
use Doctrine\DBAL\Schema\Column;
9
use Doctrine\DBAL\Schema\Constraint;
10
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
11
use Doctrine\DBAL\Schema\Identifier;
12
use Doctrine\DBAL\Schema\Index;
13
use Doctrine\DBAL\Schema\Table;
14
use Doctrine\DBAL\Schema\TableDiff;
15
use Doctrine\DBAL\TransactionIsolationLevel;
16
use Doctrine\DBAL\Types;
17
use InvalidArgumentException;
18
use function array_merge;
19
use function array_unique;
20
use function array_values;
21
use function implode;
22
use function sprintf;
23
use function sqrt;
24
use function str_replace;
25
use function strpos;
26
use function strtolower;
27
28
/**
29
 * The SqlitePlatform class describes the specifics and dialects of the SQLite
30
 * database platform.
31
 *
32
 * @todo   Rename: SQLitePlatform
33
 */
34
class SqlitePlatform extends AbstractPlatform
35
{
36
    /**
37
     * {@inheritDoc}
38 1801
     */
39
    public function getRegexpExpression() : string
40 1801
    {
41
        return 'REGEXP';
42
    }
43
44
    /**
45
     * {@inheritDoc}
46
     */
47
    public function getNowExpression($type = 'timestamp') : string
48
    {
49
        switch ($type) {
50
            case 'time':
51
                return 'time(\'now\')';
52
            case 'date':
53
                return 'date(\'now\')';
54
            case 'timestamp':
55
            default:
56
                return 'datetime(\'now\')';
57
        }
58
    }
59
60
    /**
61
     * {@inheritDoc}
62 253
     */
63
    public function getTrimExpression(string $str, int $mode = TrimMode::UNSPECIFIED, ?string $char = null) : string
64 253
    {
65
        switch ($mode) {
66 253
            case TrimMode::UNSPECIFIED:
67
            case TrimMode::BOTH:
68 252
                $trimFn = 'TRIM';
69 252
                break;
70
71
            case TrimMode::LEADING:
72 251
                $trimFn = 'LTRIM';
73 251
                break;
74
75
            case TrimMode::TRAILING:
76 253
                $trimFn = 'RTRIM';
77
                break;
78
79 253
            default:
80
                throw new InvalidArgumentException(
81
                    sprintf(
82
                        'The value of $mode is expected to be one of the TrimMode constants, %d given',
83
                        $mode
84
                    )
85
                );
86
        }
87 1801
88
        $arguments = [$str];
89 1801
90 1801
        if ($char !== null) {
91
            $arguments[] = $char;
92
        }
93 1801
94
        return sprintf('%s(%s)', $trimFn, implode(', ', $arguments));
95
    }
96
97
    /**
98
     * {@inheritDoc}
99 226
     */
100
    public function getSubstringExpression(string $string, string $start, ?string $length = null) : string
101 226
    {
102 226
        if ($length === null) {
103
            return sprintf('SUBSTR(%s, %s)', $string, $start);
104
        }
105 226
106
        return sprintf('SUBSTR(%s, %s, %s)', $string, $start, $length);
107
    }
108
109
    /**
110
     * {@inheritDoc}
111 1403
     */
112
    public function getLocateExpression(string $string, string $substring, ?string $start = null) : string
113 1403
    {
114
        if ($start === null) {
115
            return sprintf('LOCATE(%s, %s)', $string, $substring);
116
        }
117 228
118
        return sprintf('LOCATE(%s, %s, %s)', $string, $substring, $start);
119
    }
120 1403
121
    /**
122 228
     * {@inheritdoc}
123 228
     */
124 228
    protected function getDateArithmeticIntervalExpression(string $date, string $operator, string $interval, string $unit) : string
125
    {
126
        switch ($unit) {
127 228
            case DateIntervalUnit::WEEK:
128 228
                $interval = $this->multiplyInterval($interval, 7);
129 228
                $unit     = DateIntervalUnit::DAY;
130
                break;
131
132 1403
            case DateIntervalUnit::QUARTER:
133 1378
                $interval = $this->multiplyInterval($interval, 3);
134
                $unit     = DateIntervalUnit::MONTH;
135
                break;
136 1403
        }
137
138
        return 'DATETIME(' . $date . ',' . $this->getConcatExpression(
139
            $this->quoteStringLiteral($operator),
140
            $interval,
141
            $this->quoteStringLiteral(' ' . $unit)
142
        ) . ')';
143 201
    }
144
145 201
    /**
146
     * {@inheritDoc}
147
     */
148
    public function getDateDiffExpression(string $date1, string $date2) : string
149
    {
150
        return sprintf("JULIANDAY(%s, 'start of day') - JULIANDAY(%s, 'start of day')", $date1, $date2);
151 1777
    }
152
153 1
    /**
154 1776
     * {@inheritDoc}
155 1777
     */
156 1776
    protected function _getTransactionIsolationLevelSQL(int $level) : string
157 1776
    {
158 1776
        switch ($level) {
159 1777
            case TransactionIsolationLevel::READ_UNCOMMITTED:
160
                return '0';
161
            case TransactionIsolationLevel::READ_COMMITTED:
162
            case TransactionIsolationLevel::REPEATABLE_READ:
163
            case TransactionIsolationLevel::SERIALIZABLE:
164
                return '1';
165
            default:
166
                return parent::_getTransactionIsolationLevelSQL($level);
167
        }
168 1777
    }
169
170 1777
    /**
171
     * {@inheritDoc}
172
     */
173
    public function getSetTransactionIsolationSQL(int $level) : string
174
    {
175
        return 'PRAGMA read_uncommitted = ' . $this->_getTransactionIsolationLevelSQL($level);
176 1762
    }
177
178 1762
    /**
179
     * {@inheritDoc}
180
     */
181
    public function prefersIdentityColumns() : bool
182
    {
183
        return true;
184 965
    }
185
186 965
    /**
187
     * {@inheritDoc}
188
     */
189
    public function getBooleanTypeDeclarationSQL(array $columnDef) : string
190
    {
191
        return 'BOOLEAN';
192 1941
    }
193
194 1941
    /**
195
     * {@inheritDoc}
196
     */
197
    public function getIntegerTypeDeclarationSQL(array $columnDef) : string
198
    {
199
        return 'INTEGER' . $this->_getCommonIntegerTypeDeclarationSQL($columnDef);
200 1733
    }
201
202
    /**
203 1733
     * {@inheritDoc}
204 1733
     */
205
    public function getBigIntTypeDeclarationSQL(array $columnDef) : string
206
    {
207 1673
        //  SQLite autoincrement is implicit for INTEGER PKs, but not for BIGINT fields.
208
        if (! empty($columnDef['autoincrement'])) {
209
            return $this->getIntegerTypeDeclarationSQL($columnDef);
210
        }
211
212
        return 'BIGINT' . $this->_getCommonIntegerTypeDeclarationSQL($columnDef);
213 1706
    }
214
215
    /**
216 1706
     * {@inheritDoc}
217 1706
     */
218
    public function getTinyIntTypeDeclarationSql(array $field) : string
219
    {
220 1705
        //  SQLite autoincrement is implicit for INTEGER PKs, but not for TINYINT fields.
221
        if (! empty($field['autoincrement'])) {
222
            return $this->getIntegerTypeDeclarationSQL($field);
223
        }
224
225
        return 'TINYINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
226 1783
    }
227
228
    /**
229 1783
     * {@inheritDoc}
230 1783
     */
231
    public function getSmallIntTypeDeclarationSQL(array $columnDef) : string
232
    {
233 1760
        //  SQLite autoincrement is implicit for INTEGER PKs, but not for SMALLINT fields.
234
        if (! empty($columnDef['autoincrement'])) {
235
            return $this->getIntegerTypeDeclarationSQL($columnDef);
236
        }
237
238
        return 'SMALLINT' . $this->_getCommonIntegerTypeDeclarationSQL($columnDef);
239 1657
    }
240
241
    /**
242 1657
     * {@inheritDoc}
243 1657
     */
244
    public function getMediumIntTypeDeclarationSql(array $field) : string
245
    {
246 1657
        //  SQLite autoincrement is implicit for INTEGER PKs, but not for MEDIUMINT fields.
247
        if (! empty($field['autoincrement'])) {
248
            return $this->getIntegerTypeDeclarationSQL($field);
249
        }
250
251
        return 'MEDIUMINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
252 254
    }
253
254 254
    /**
255
     * {@inheritDoc}
256
     */
257
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration) : string
258
    {
259
        return 'DATETIME';
260 227
    }
261
262 227
    /**
263
     * {@inheritDoc}
264
     */
265
    public function getDateTypeDeclarationSQL(array $fieldDeclaration) : string
266
    {
267
        return 'DATE';
268 164
    }
269
270 164
    /**
271
     * {@inheritDoc}
272
     */
273
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration) : string
274
    {
275
        return 'TIME';
276 1941
    }
277
278
    /**
279 1941
     * {@inheritDoc}
280 1881
     */
281
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef) : string
282
    {
283 1915
        // sqlite autoincrement is only possible for the primary key
284
        if (! empty($columnDef['autoincrement'])) {
285
            return ' PRIMARY KEY AUTOINCREMENT';
286
        }
287
288
        return ! empty($columnDef['unsigned']) ? ' UNSIGNED' : '';
289 1495
    }
290
291 1495
    /**
292 1495
     * {@inheritDoc}
293 1495
     */
294 1495
    public function getForeignKeyDeclarationSQL(ForeignKeyConstraint $foreignKey) : string
295 1495
    {
296 1495
        return parent::getForeignKeyDeclarationSQL(new ForeignKeyConstraint(
297
            $foreignKey->getQuotedLocalColumns($this),
298
            str_replace('.', '__', $foreignKey->getQuotedForeignTableName($this)),
299
            $foreignKey->getQuotedForeignColumns($this),
300
            $foreignKey->getName(),
301
            $foreignKey->getOptions()
302
        ));
303 1714
    }
304
305 1714
    /**
306 1714
     * {@inheritDoc}
307
     */
308 1714
    protected function _getCreateTableSQL(string $tableName, array $columns, array $options = []) : array
309
    {
310
        $tableName   = str_replace('.', '__', $tableName);
311
        $queryFields = $this->getColumnDeclarationListSQL($columns);
312
313
        if (isset($options['uniqueConstraints']) && ! empty($options['uniqueConstraints'])) {
314 1714
            foreach ($options['uniqueConstraints'] as $name => $definition) {
315
                $queryFields .= ', ' . $this->getUniqueConstraintDeclarationSQL($name, $definition);
316 1714
            }
317 1713
        }
318 1495
319
        $queryFields .= $this->getNonAutoincrementPrimaryKeyDefinition($columns, $options);
320
321
        if (isset($options['foreignKeys'])) {
322 1714
            foreach ($options['foreignKeys'] as $foreignKey) {
323
                $queryFields .= ', ' . $this->getForeignKeyDeclarationSQL($foreignKey);
324 1714
            }
325 1479
        }
326
327
        $query = ['CREATE TABLE ' . $tableName . ' (' . $queryFields . ')'];
328 1702
329 1558
        if (isset($options['alter']) && $options['alter'] === true) {
330 1558
            return $query;
331
        }
332
333
        if (isset($options['indexes']) && ! empty($options['indexes'])) {
334 1702
            foreach ($options['indexes'] as $indexDef) {
335
                $query[] = $this->getCreateIndexSQL($indexDef, $tableName);
336
            }
337
        }
338
339
        if (isset($options['unique']) && ! empty($options['unique'])) {
340 1702
            foreach ($options['unique'] as $indexDef) {
341
                $query[] = $this->getCreateIndexSQL($indexDef, $tableName);
342
            }
343
        }
344
345
        return $query;
346
    }
347
348
    /**
349 1714
     * Generate a PRIMARY KEY definition if no autoincrement value is used
350
     *
351 1714
     * @param mixed[][] $columns
352 1317
     * @param mixed[]   $options
353
     */
354
    private function getNonAutoincrementPrimaryKeyDefinition(array $columns, array $options) : string
355 1700
    {
356
        if (empty($options['primary'])) {
357 1700
            return '';
358 1700
        }
359 1654
360
        $keyColumns = array_unique(array_values($options['primary']));
361
362
        foreach ($keyColumns as $keyColumn) {
363 1605
            if (! empty($columns[$keyColumn]['autoincrement'])) {
364
                return '';
365
            }
366
        }
367
368
        return ', PRIMARY KEY(' . implode(', ', $keyColumns) . ')';
369 1811
    }
370
371 1811
    /**
372 1743
     * {@inheritDoc}
373 1811
     */
374
    protected function getVarcharTypeDeclarationSQLSnippet(?int $length, bool $fixed) : string
375
    {
376
        return $fixed
377
            ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)')
378
            : ($length ? 'VARCHAR(' . $length . ')' : 'TEXT');
379 1464
    }
380
381 1464
    /**
382
     * {@inheritdoc}
383
     */
384
    protected function getBinaryTypeDeclarationSQLSnippet(?int $length, bool $fixed) : string
385
    {
386
        return 'BLOB';
387 505
    }
388
389 505
    /**
390
     * {@inheritdoc}
391
     */
392
    public function getBinaryMaxLength() : int
393
    {
394
        return 0;
395 1465
    }
396
397 1465
    /**
398
     * {@inheritdoc}
399
     */
400
    public function getBinaryDefaultLength() : int
401
    {
402
        return 0;
403 746
    }
404
405 746
    /**
406
     * {@inheritDoc}
407
     */
408
    public function getClobTypeDeclarationSQL(array $field) : string
409
    {
410
        return 'CLOB';
411 1297
    }
412
413 1297
    /**
414
     * {@inheritDoc}
415 1297
     */
416 1
    public function getListTableConstraintsSQL(string $table) : string
417 1297
    {
418
        $table = str_replace('.', '__', $table);
419
420
        return sprintf(
421
            "SELECT sql FROM sqlite_master WHERE type='index' AND tbl_name = %s AND sql NOT NULL ORDER BY name",
422
            $this->quoteStringLiteral($table)
423
        );
424 1405
    }
425
426 1405
    /**
427
     * {@inheritDoc}
428 1405
     */
429
    public function getListTableColumnsSQL(string $table, ?string $database = null) : string
430
    {
431
        $table = str_replace('.', '__', $table);
432
433
        return sprintf('PRAGMA table_info(%s)', $this->quoteStringLiteral($table));
434 1382
    }
435
436 1382
    /**
437
     * {@inheritDoc}
438 1382
     */
439
    public function getListTableIndexesSQL(string $table, ?string $currentDatabase = null) : string
440
    {
441
        $table = str_replace('.', '__', $table);
442
443
        return sprintf('PRAGMA index_list(%s)', $this->quoteStringLiteral($table));
444 304
    }
445
446
    /**
447
     * {@inheritDoc}
448 304
     */
449
    public function getListTablesSQL() : string
450
    {
451
        return "SELECT name FROM sqlite_master WHERE type = 'table' AND name != 'sqlite_sequence' AND name != 'geometry_columns' AND name != 'spatial_ref_sys' "
452
             . 'UNION ALL SELECT name FROM sqlite_temp_master '
453
             . "WHERE type = 'table' ORDER BY name";
454 155
    }
455
456 155
    /**
457
     * {@inheritDoc}
458
     */
459
    public function getListViewsSQL(?string $database) : string
460
    {
461
        return "SELECT name, sql FROM sqlite_master WHERE type='view' AND sql NOT NULL";
462 155
    }
463
464 155
    /**
465
     * {@inheritDoc}
466
     */
467
    public function getCreateViewSQL(string $name, string $sql) : string
468
    {
469
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
470 155
    }
471
472 155
    /**
473
     * {@inheritDoc}
474
     */
475
    public function getDropViewSQL(string $name) : string
476
    {
477
        return 'DROP VIEW ' . $name;
478 1495
    }
479
480 1495
    /**
481
     * {@inheritDoc}
482 1495
     */
483 1495
    public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey) : string
484
    {
485 1495
        $query = parent::getAdvancedForeignKeyOptionsSQL($foreignKey);
486
487
        $query .= ($foreignKey->hasOption('deferrable') && $foreignKey->getOption('deferrable') !== false ? ' ' : ' NOT ') . 'DEFERRABLE';
488
        $query .= ' INITIALLY ' . ($foreignKey->hasOption('deferred') && $foreignKey->getOption('deferred') !== false ? 'DEFERRED' : 'IMMEDIATE');
489
490
        return $query;
491 154
    }
492
493 154
    /**
494
     * {@inheritDoc}
495
     */
496
    public function supportsIdentityColumns() : bool
497
    {
498
        return true;
499 1306
    }
500
501 1306
    /**
502
     * {@inheritDoc}
503
     */
504
    public function supportsColumnCollation() : bool
505
    {
506
        return true;
507 1718
    }
508
509 1718
    /**
510
     * {@inheritDoc}
511
     */
512
    public function supportsInlineColumnComments() : bool
513
    {
514
        return true;
515 2014
    }
516
517 2014
    /**
518
     * {@inheritDoc}
519
     */
520
    public function getName() : string
521
    {
522
        return 'sqlite';
523 792
    }
524
525 792
    /**
526 792
     * {@inheritDoc}
527
     */
528 792
    public function getTruncateTableSQL(string $tableName, bool $cascade = false) : string
529
    {
530
        $tableIdentifier = new Identifier($tableName);
531
        $tableName       = str_replace('.', '__', $tableIdentifier->getQuotedName($this));
532
533
        return 'DELETE FROM ' . $tableName;
534
    }
535
536
    /**
537
     * User-defined function for Sqlite that is used with PDO::sqliteCreateFunction().
538
     *
539
     * @param int|float $value
540
     */
541
    public static function udfSqrt($value) : float
542
    {
543
        return sqrt($value);
544
    }
545
546
    /**
547
     * User-defined function for Sqlite that implements MOD(a, b).
548
     */
549
    public static function udfMod(int $a, int $b) : int
550
    {
551
        return $a % $b;
552
    }
553
554
    public static function udfLocate(string $str, string $substr, int $offset = 0) : int
555
    {
556
        // SQL's LOCATE function works on 1-based positions, while PHP's strpos works on 0-based positions.
557
        // So we have to make them compatible if an offset is given.
558
        if ($offset > 0) {
559
            $offset -= 1;
560
        }
561
562
        $pos = strpos($str, $substr, $offset);
563 226
564
        if ($pos !== false) {
565
            return $pos + 1;
566
        }
567 226
568 226
        return 0;
569
    }
570
571 226
    /**
572
     * {@inheritDoc}
573 226
     */
574 226
    public function getForUpdateSql() : string
575
    {
576
        return '';
577 226
    }
578
579
    /**
580
     * {@inheritDoc}
581
     */
582
    public function getInlineColumnCommentSQL(?string $comment) : string
583
    {
584
        if ($comment === null || $comment === '') {
585
            return '';
586
        }
587
588
        return '--' . str_replace("\n", "\n--", $comment) . "\n";
589
    }
590
591 572
    /**
592
     * {@inheritDoc}
593 572
     */
594
    protected function initializeDoctrineTypeMappings() : void
595
    {
596
        $this->doctrineTypeMapping = [
597
            'bigint'           => 'bigint',
598
            'bigserial'        => 'bigint',
599 1201
            'blob'             => 'blob',
600
            'boolean'          => 'boolean',
601 1201
            'char'             => 'string',
602
            'clob'             => 'text',
603
            'date'             => 'date',
604
            'datetime'         => 'datetime',
605
            'decimal'          => 'decimal',
606
            'double'           => 'float',
607
            'double precision' => 'float',
608
            'float'            => 'float',
609
            'image'            => 'string',
610
            'int'              => 'integer',
611
            'integer'          => 'integer',
612
            'longtext'         => 'text',
613
            'longvarchar'      => 'string',
614
            'mediumint'        => 'integer',
615
            'mediumtext'       => 'text',
616
            'ntext'            => 'string',
617
            'numeric'          => 'decimal',
618
            'nvarchar'         => 'string',
619
            'real'             => 'float',
620
            'serial'           => 'integer',
621
            'smallint'         => 'smallint',
622
            'string'           => 'string',
623
            'text'             => 'text',
624
            'time'             => 'time',
625
            'timestamp'        => 'datetime',
626
            'tinyint'          => 'boolean',
627
            'tinytext'         => 'text',
628
            'varchar'          => 'string',
629
            'varchar2'         => 'string',
630
        ];
631
    }
632
633
    /**
634
     * {@inheritDoc}
635
     */
636 1201
    protected function getReservedKeywordsClass() : string
637
    {
638
        return Keywords\SQLiteKeywords::class;
639
    }
640
641 1728
    /**
642
     * {@inheritDoc}
643 1728
     */
644
    protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff) : array
645
    {
646
        if (! $diff->fromTable instanceof Table) {
647
            throw new DBALException('Sqlite platform requires for alter table the table diff with reference to original table schema');
648
        }
649 1479
650
        $sql = [];
651 1479
        foreach ($diff->fromTable->getIndexes() as $index) {
652
            if ($index->isPrimary()) {
653
                continue;
654
            }
655 1479
656 1479
            $sql[] = $this->getDropIndexSQL($index, $diff->name);
657 1473
        }
658 1471
659
        return $sql;
660
    }
661 1470
662
    /**
663
     * {@inheritDoc}
664 1479
     */
665
    protected function getPostAlterTableIndexForeignKeySQL(TableDiff $diff) : array
666
    {
667
        if (! $diff->fromTable instanceof Table) {
668
            throw new DBALException('Sqlite platform requires for alter table the table diff with reference to original table schema');
669
        }
670 1479
671
        $sql       = [];
672 1479
        $tableName = $diff->getNewName();
673
674
        if ($tableName === false) {
675
            $tableName = $diff->getName($this);
676 1479
        }
677 1479
678
        foreach ($this->getIndexesInAlteredTable($diff) as $index) {
679 1479
            if ($index->isPrimary()) {
680 901
                continue;
681
            }
682
683 1479
            $sql[] = $this->getCreateIndexSQL($index, $tableName->getQuotedName($this));
684 1473
        }
685 1471
686
        return $sql;
687
    }
688 1472
689
    /**
690
     * {@inheritDoc}
691 1479
     */
692
    protected function doModifyLimitQuery(string $query, ?int $limit, int $offset) : string
693
    {
694
        if ($limit === null && $offset > 0) {
695
            $limit = -1;
696
        }
697 1692
698
        return parent::doModifyLimitQuery($query, $limit, $offset);
699 1692
    }
700 1666
701
    /**
702
     * {@inheritDoc}
703 1692
     */
704
    public function getBlobTypeDeclarationSQL(array $field) : string
705
    {
706
        return 'BLOB';
707
    }
708
709 262
    /**
710
     * {@inheritDoc}
711 262
     */
712
    public function getTemporaryTableName(string $tableName) : string
713
    {
714
        $tableName = str_replace('.', '__', $tableName);
715
716
        return $tableName;
717 111
    }
718
719 111
    /**
720
     * {@inheritDoc}
721 111
     *
722
     * Sqlite Platform emulates schema by underscoring each dot and generating tables
723
     * into the default database.
724
     *
725
     * This hack is implemented to be able to use SQLite as testdriver when
726
     * using schema supporting databases.
727
     */
728
    public function canEmulateSchemas() : bool
729
    {
730
        return true;
731
    }
732
733
    /**
734
     * {@inheritDoc}
735
     */
736
    public function supportsForeignKeyConstraints() : bool
737
    {
738
        return false;
739
    }
740
741 1566
    /**
742
     * {@inheritDoc}
743 1566
     */
744
    public function getCreatePrimaryKeySQL(Index $index, $table) : string
745
    {
746
        throw new DBALException('Sqlite platform does not support alter primary key.');
747
    }
748
749
    /**
750
     * {@inheritdoc}
751
     */
752
    public function getCreateForeignKeySQL(ForeignKeyConstraint $foreignKey, $table) : string
753
    {
754
        throw new DBALException('Sqlite platform does not support alter foreign key.');
755
    }
756
757 1586
    /**
758
     * {@inheritdoc}
759 1586
     */
760
    public function getDropForeignKeySQL($foreignKey, $table) : string
761
    {
762
        throw new DBALException('Sqlite platform does not support alter foreign key.');
763
    }
764
765
    /**
766
     * {@inheritDoc}
767
     */
768
    public function getCreateConstraintSQL(Constraint $constraint, $table) : string
769
    {
770
        throw new DBALException('Sqlite platform does not support alter constraint.');
771
    }
772
773 1561
    /**
774
     * {@inheritDoc}
775 1561
     */
776
    public function getCreateTableSQL(Table $table, int $createFlags = self::CREATE_INDEXES | self::CREATE_FOREIGNKEYS) : array
777
    {
778
        return parent::getCreateTableSQL($table, $createFlags);
779
    }
780
781 1715
    /**
782
     * {@inheritDoc}
783 1715
     */
784
    public function getListTableForeignKeysSQL(string $table, ?string $database = null) : string
785 1715
    {
786
        $table = str_replace('.', '__', $table);
787
788
        return sprintf('PRAGMA foreign_key_list(%s)', $this->quoteStringLiteral($table));
789
    }
790
791 1374
    /**
792
     * {@inheritDoc}
793 1374
     */
794
    public function getAlterTableSQL(TableDiff $diff) : array
795 1374
    {
796
        $sql = $this->getSimpleAlterTableSQL($diff);
797
        if ($sql !== false) {
0 ignored issues
show
introduced by
The condition $sql !== false is always false.
Loading history...
798
            return $sql;
799
        }
800
801 1596
        $fromTable = $diff->fromTable;
802
        if (! $fromTable instanceof Table) {
803 1596
            throw new DBALException('Sqlite platform requires for alter table the table diff with reference to original table schema');
804 1596
        }
805 1582
806
        $table = clone $fromTable;
807
808 1550
        $columns        = [];
809 1550
        $oldColumnNames = [];
810 1442
        $newColumnNames = [];
811
        $columnSql      = [];
812
813 1479
        foreach ($table->getColumns() as $columnName => $column) {
814
            $columnName                  = strtolower($columnName);
815 1479
            $columns[$columnName]        = $column;
816 1479
            $oldColumnNames[$columnName] = $newColumnNames[$columnName] = $column->getQuotedName($this);
817 1479
        }
818 1479
819
        foreach ($diff->removedColumns as $columnName => $column) {
820 1479
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
821 1478
                continue;
822 1478
            }
823 1478
824
            $columnName = strtolower($columnName);
825
            if (! isset($columns[$columnName])) {
826 1479
                continue;
827 1471
            }
828
829
            unset(
830
                $columns[$columnName],
831 1471
                $oldColumnNames[$columnName],
832 1471
                $newColumnNames[$columnName]
833
            );
834
        }
835
836
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
837 1471
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
838 1471
                continue;
839 1471
            }
840
841
            $oldColumnName = strtolower($oldColumnName);
842
            if (isset($columns[$oldColumnName])) {
843 1479
                unset($columns[$oldColumnName]);
844 1373
            }
845
846
            $columns[strtolower($column->getName())] = $column;
847
848 1373
            if (! isset($newColumnNames[$oldColumnName])) {
849 1373
                continue;
850 1373
            }
851
852
            $newColumnNames[$oldColumnName] = $column->getQuotedName($this);
853 1373
        }
854
855 1373
        foreach ($diff->changedColumns as $oldColumnName => $columnDiff) {
856
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
857
                continue;
858
            }
859 1373
860
            if (isset($columns[$oldColumnName])) {
861
                unset($columns[$oldColumnName]);
862 1479
            }
863 940
864
            $columns[strtolower($columnDiff->column->getName())] = $columnDiff->column;
865
866
            if (! isset($newColumnNames[$oldColumnName])) {
867 940
                continue;
868 939
            }
869
870
            $newColumnNames[$oldColumnName] = $columnDiff->column->getQuotedName($this);
871 940
        }
872
873 940
        foreach ($diff->addedColumns as $columnName => $column) {
874 553
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
875
                continue;
876
            }
877 939
878
            $columns[strtolower($columnName)] = $column;
879
        }
880 1479
881 941
        $sql      = [];
882
        $tableSql = [];
883
884
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
885 941
            $dataTable = new Table('__temp__' . $table->getName());
886
887
            $newTable = new Table($table->getQuotedName($this), $columns, $this->getPrimaryIndexInAlteredTable($diff), [], $this->getForeignKeysInAlteredTable($diff), $table->getOptions());
888 1479
            $newTable->addOption('alter', true);
889 1479
890
            $sql = $this->getPreAlterTableIndexForeignKeySQL($diff);
891 1479
            //$sql = array_merge($sql, $this->getCreateTableSQL($dataTable, 0));
892 1479
            $sql[] = sprintf('CREATE TEMPORARY TABLE %s AS SELECT %s FROM %s', $dataTable->getQuotedName($this), implode(', ', $oldColumnNames), $table->getQuotedName($this));
893
            $sql[] = $this->getDropTableSQL($fromTable);
894 1479
895 1479
            $sql   = array_merge($sql, $this->getCreateTableSQL($newTable));
896
            $sql[] = sprintf('INSERT INTO %s (%s) SELECT %s FROM %s', $newTable->getQuotedName($this), implode(', ', $newColumnNames), implode(', ', $oldColumnNames), $dataTable->getQuotedName($this));
897 1479
            $sql[] = $this->getDropTableSQL($dataTable);
898
899 1479
            $newName = $diff->getNewName();
900 1479
901
            if ($newName !== false) {
902 1479
                $sql[] = sprintf(
903 1479
                    'ALTER TABLE %s RENAME TO %s',
904 1479
                    $newTable->getQuotedName($this),
905
                    $newName->getQuotedName($this)
906 1479
                );
907
            }
908 1479
909 1371
            $sql = array_merge($sql, $this->getPostAlterTableIndexForeignKeySQL($diff));
910 3
        }
911 1371
912 1371
        return array_merge($sql, $tableSql, $columnSql);
913
    }
914
915
    /**
916 1479
     * @return string[]|false
917
     */
918
    private function getSimpleAlterTableSQL(TableDiff $diff)
919 1479
    {
920
        // Suppress changes on integer type autoincrement columns.
921
        foreach ($diff->changedColumns as $oldColumnName => $columnDiff) {
922
            if (! $columnDiff->fromColumn instanceof Column ||
923
                ! $columnDiff->column instanceof Column ||
924
                ! $columnDiff->column->getAutoincrement() ||
925 1596
                ! $columnDiff->column->getType() instanceof Types\IntegerType
926
            ) {
927
                continue;
928 1596
            }
929 960
930 956
            if (! $columnDiff->hasChanged('type') && $columnDiff->hasChanged('unsigned')) {
931 956
                unset($diff->changedColumns[$oldColumnName]);
932 960
933
                continue;
934 940
            }
935
936
            $fromColumnType = $columnDiff->fromColumn->getType();
937 172
938 169
            if (! ($fromColumnType instanceof Types\SmallIntType) && ! ($fromColumnType instanceof Types\BigIntType)) {
939
                continue;
940 169
            }
941
942
            unset($diff->changedColumns[$oldColumnName]);
943 172
        }
944
945 172
        if (! empty($diff->renamedColumns) || ! empty($diff->addedForeignKeys) || ! empty($diff->addedIndexes)
946
                || ! empty($diff->changedColumns) || ! empty($diff->changedForeignKeys) || ! empty($diff->changedIndexes)
947
                || ! empty($diff->removedColumns) || ! empty($diff->removedForeignKeys) || ! empty($diff->removedIndexes)
948
                || ! empty($diff->renamedIndexes)
949 172
        ) {
950
            return false;
951
        }
952 1596
953 1591
        $table = new Table($diff->name);
954 1587
955 1596
        $sql       = [];
956
        $tableSql  = [];
957 1479
        $columnSql = [];
958
959
        foreach ($diff->addedColumns as $column) {
960 1584
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
961
                continue;
962 1584
            }
963 1584
964 1584
            $field = array_merge(['unique' => null, 'autoincrement' => null, 'default' => null], $column->toArray());
965
            $type  = $field['type'];
966 1584
            switch (true) {
967 1467
                case isset($field['columnDefinition']) || $field['autoincrement'] || $field['unique']:
968
                case $type instanceof Types\DateTimeType && $field['default'] === $this->getCurrentTimestampSQL():
969
                case $type instanceof Types\DateType && $field['default'] === $this->getCurrentDateSQL():
970
                case $type instanceof Types\TimeType && $field['default'] === $this->getCurrentTimeSQL():
971 1467
                    return false;
972 1467
            }
973
974 1467
            $field['name'] = $column->getQuotedName($this);
975 1466
            if ($type instanceof Types\StringType && $field['length'] === null) {
976 1466
                $field['length'] = 255;
977 1465
            }
978 1442
979
            $sql[] = 'ALTER TABLE ' . $table->getQuotedName($this) . ' ADD COLUMN ' . $this->getColumnDeclarationSQL($field['name'], $field);
980
        }
981 1465
982 1465
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
983 1465
            if ($diff->newName !== false) {
984
                $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

984
                $newTable = new Identifier(/** @scrutinizer ignore-type */ $diff->newName);
Loading history...
985
                $sql[]    = 'ALTER TABLE ' . $table->getQuotedName($this) . ' RENAME TO ' . $newTable->getQuotedName($this);
986 1465
            }
987
        }
988
989 1582
        return array_merge($sql, $tableSql, $columnSql);
990 1582
    }
991 178
992 178
    /**
993
     * @return string[]
994
     */
995
    private function getColumnNamesInAlteredTable(TableDiff $diff) : array
996 1582
    {
997
        $columns = [];
998
999
        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

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