Failed Conditions
Pull Request — develop (#3348)
by Sergei
91:36 queued 30:26
created

SqlitePlatform::getForeignKeysInAlteredTable()   B

Complexity

Conditions 11
Paths 120

Size

Total Lines 55
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 26
CRAP Score 11.044

Importance

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

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
     */
39
    public function getRegexpExpression() : string
40 1827
    {
41
        return 'REGEXP';
42 1827
    }
43
44
    /**
45
     * {@inheritDoc}
46
     */
47
    public function getNowExpression(string $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
     */
63
    public function getTrimExpression(string $str, int $mode = TrimMode::UNSPECIFIED, ?string $char = null) : string
64 286
    {
65
        switch ($mode) {
66 286
            case TrimMode::UNSPECIFIED:
67
            case TrimMode::BOTH:
68
                $trimFn = 'TRIM';
69 286
                break;
70 286
71
            case TrimMode::LEADING:
72
                $trimFn = 'LTRIM';
73 285
                break;
74 285
75
            case TrimMode::TRAILING:
76
                $trimFn = 'RTRIM';
77 285
                break;
78 285
79
            default:
80
                throw new InvalidArgumentException(
81 261
                    sprintf(
82 261
                        'The value of $mode is expected to be one of the TrimMode constants, %d given.',
83
                        $mode
84 261
                    )
85
                );
86
        }
87
88
        $arguments = [$str];
89 286
90
        if ($char !== null) {
91 286
            $arguments[] = $char;
92 283
        }
93
94
        return sprintf('%s(%s)', $trimFn, implode(', ', $arguments));
95 286
    }
96
97
    /**
98
     * {@inheritDoc}
99
     */
100
    public function getSubstringExpression(string $string, string $start, ?string $length = null) : string
101 1980
    {
102
        if ($length === null) {
103 1980
            return sprintf('SUBSTR(%s, %s)', $string, $start);
104 1980
        }
105
106
        return sprintf('SUBSTR(%s, %s, %s)', $string, $start, $length);
107 1979
    }
108
109
    /**
110
     * {@inheritDoc}
111
     */
112
    public function getLocateExpression(string $string, string $substring, ?string $start = null) : string
113 227
    {
114
        if ($start === null) {
115 227
            return sprintf('LOCATE(%s, %s)', $string, $substring);
116 227
        }
117
118
        return sprintf('LOCATE(%s, %s, %s)', $string, $substring, $start);
119 227
    }
120
121
    /**
122
     * {@inheritdoc}
123
     */
124
    protected function getDateArithmeticIntervalExpression(string $date, string $operator, string $interval, string $unit) : string
125 1464
    {
126
        switch ($unit) {
127 1464
            case DateIntervalUnit::WEEK:
128
                $interval = $this->multiplyInterval($interval, 7);
129 244
                $unit     = DateIntervalUnit::DAY;
130 244
                break;
131 244
132
            case DateIntervalUnit::QUARTER:
133
                $interval = $this->multiplyInterval($interval, 3);
134 236
                $unit     = DateIntervalUnit::MONTH;
135 236
                break;
136 236
        }
137
138
        return 'DATETIME(' . $date . ',' . $this->getConcatExpression(
139 1464
            $this->quoteStringLiteral($operator),
140 1464
            $interval,
141 4
            $this->quoteStringLiteral(' ' . $unit)
142 1464
        ) . ')';
143 1464
    }
144
145
    /**
146
     * {@inheritDoc}
147
     */
148
    public function getDateDiffExpression(string $date1, string $date2) : string
149 199
    {
150
        return sprintf("JULIANDAY(%s, 'start of day') - JULIANDAY(%s, 'start of day')", $date1, $date2);
151 199
    }
152
153
    /**
154
     * {@inheritDoc}
155
     */
156
    protected function _getTransactionIsolationLevelSQL(int $level) : string
157 1827
    {
158
        switch ($level) {
159 2
            case TransactionIsolationLevel::READ_UNCOMMITTED:
160 1825
                return '0';
161 1827
            case TransactionIsolationLevel::READ_COMMITTED:
162 1825
            case TransactionIsolationLevel::REPEATABLE_READ:
163 1825
            case TransactionIsolationLevel::SERIALIZABLE:
164 1825
                return '1';
165 1827
            default:
166
                return parent::_getTransactionIsolationLevelSQL($level);
167
        }
168
    }
169
170
    /**
171
     * {@inheritDoc}
172
     */
173
    public function getSetTransactionIsolationSQL(int $level) : string
174 1827
    {
175
        return 'PRAGMA read_uncommitted = ' . $this->_getTransactionIsolationLevelSQL($level);
176 1827
    }
177
178
    /**
179
     * {@inheritDoc}
180
     */
181
    public function prefersIdentityColumns() : bool
182 1810
    {
183
        return true;
184 1810
    }
185
186
    /**
187
     * {@inheritDoc}
188
     */
189
    public function getBooleanTypeDeclarationSQL(array $columnDef) : string
190 999
    {
191
        return 'BOOLEAN';
192 999
    }
193
194
    /**
195
     * {@inheritDoc}
196
     */
197
    public function getIntegerTypeDeclarationSQL(array $columnDef) : string
198 2045
    {
199
        return 'INTEGER' . $this->_getCommonIntegerTypeDeclarationSQL($columnDef);
200 2045
    }
201
202
    /**
203
     * {@inheritDoc}
204
     */
205
    public function getBigIntTypeDeclarationSQL(array $columnDef) : string
206 1777
    {
207
        //  SQLite autoincrement is implicit for INTEGER PKs, but not for BIGINT fields.
208
        if (! empty($columnDef['autoincrement'])) {
209 1777
            return $this->getIntegerTypeDeclarationSQL($columnDef);
210 1777
        }
211
212
        return 'BIGINT' . $this->_getCommonIntegerTypeDeclarationSQL($columnDef);
213 1715
    }
214
215
    /**
216
     * {@inheritDoc}
217
     */
218
    public function getTinyIntTypeDeclarationSql(array $field) : string
219 1754
    {
220
        //  SQLite autoincrement is implicit for INTEGER PKs, but not for TINYINT fields.
221
        if (! empty($field['autoincrement'])) {
222 1754
            return $this->getIntegerTypeDeclarationSQL($field);
223 1754
        }
224
225
        return 'TINYINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
226 1752
    }
227
228
    /**
229
     * {@inheritDoc}
230
     */
231
    public function getSmallIntTypeDeclarationSQL(array $columnDef) : string
232 1829
    {
233
        //  SQLite autoincrement is implicit for INTEGER PKs, but not for SMALLINT fields.
234
        if (! empty($columnDef['autoincrement'])) {
235 1829
            return $this->getIntegerTypeDeclarationSQL($columnDef);
236 1829
        }
237
238
        return 'SMALLINT' . $this->_getCommonIntegerTypeDeclarationSQL($columnDef);
239 1806
    }
240
241
    /**
242
     * {@inheritDoc}
243
     */
244
    public function getMediumIntTypeDeclarationSql(array $field) : string
245 1702
    {
246
        //  SQLite autoincrement is implicit for INTEGER PKs, but not for MEDIUMINT fields.
247
        if (! empty($field['autoincrement'])) {
248 1702
            return $this->getIntegerTypeDeclarationSQL($field);
249 1702
        }
250
251
        return 'MEDIUMINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
252 1702
    }
253
254
    /**
255
     * {@inheritDoc}
256
     */
257
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration) : string
258 287
    {
259
        return 'DATETIME';
260 287
    }
261
262
    /**
263
     * {@inheritDoc}
264
     */
265
    public function getDateTypeDeclarationSQL(array $fieldDeclaration) : string
266 228
    {
267
        return 'DATE';
268 228
    }
269
270
    /**
271
     * {@inheritDoc}
272
     */
273
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration) : string
274 163
    {
275
        return 'TIME';
276 163
    }
277
278
    /**
279
     * {@inheritDoc}
280
     */
281
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef) : string
282 2045
    {
283
        // sqlite autoincrement is only possible for the primary key
284
        if (! empty($columnDef['autoincrement'])) {
285 2045
            return ' PRIMARY KEY AUTOINCREMENT';
286 1936
        }
287
288
        return ! empty($columnDef['unsigned']) ? ' UNSIGNED' : '';
289 2015
    }
290
291
    /**
292
     * {@inheritDoc}
293
     */
294
    public function getForeignKeyDeclarationSQL(ForeignKeyConstraint $foreignKey) : string
295 1533
    {
296
        return parent::getForeignKeyDeclarationSQL(new ForeignKeyConstraint(
297 1533
            $foreignKey->getQuotedLocalColumns($this),
298 1533
            str_replace('.', '__', $foreignKey->getQuotedForeignTableName($this)),
299 1533
            $foreignKey->getQuotedForeignColumns($this),
300 1533
            $foreignKey->getName(),
301 1533
            $foreignKey->getOptions()
302 1533
        ));
303
    }
304
305
    /**
306
     * {@inheritDoc}
307
     */
308
    protected function _getCreateTableSQL(string $tableName, array $columns, array $options = []) : array
309 1811
    {
310
        $tableName   = str_replace('.', '__', $tableName);
311 1811
        $queryFields = $this->getColumnDeclarationListSQL($columns);
312 1811
313
        if (isset($options['uniqueConstraints']) && ! empty($options['uniqueConstraints'])) {
314 1811
            foreach ($options['uniqueConstraints'] as $name => $definition) {
315
                $queryFields .= ', ' . $this->getUniqueConstraintDeclarationSQL($name, $definition);
316
            }
317
        }
318
319
        $queryFields .= $this->getNonAutoincrementPrimaryKeyDefinition($columns, $options);
320 1811
321
        if (isset($options['foreignKeys'])) {
322 1811
            foreach ($options['foreignKeys'] as $foreignKey) {
323 1809
                $queryFields .= ', ' . $this->getForeignKeyDeclarationSQL($foreignKey);
324 1533
            }
325
        }
326
327
        $query = ['CREATE TABLE ' . $tableName . ' (' . $queryFields . ')'];
328 1811
329
        if (isset($options['alter']) && $options['alter'] === true) {
330 1811
            return $query;
331 1523
        }
332
333
        if (isset($options['indexes']) && ! empty($options['indexes'])) {
334 1787
            foreach ($options['indexes'] as $indexDef) {
335 1594
                $query[] = $this->getCreateIndexSQL($indexDef, $tableName);
336 1594
            }
337
        }
338
339
        if (isset($options['unique']) && ! empty($options['unique'])) {
340 1787
            foreach ($options['unique'] as $indexDef) {
341
                $query[] = $this->getCreateIndexSQL($indexDef, $tableName);
342
            }
343
        }
344
345
        return $query;
346 1787
    }
347
348
    /**
349
     * Generate a PRIMARY KEY definition if no autoincrement value is used
350
     *
351
     * @param mixed[][] $columns
352
     * @param mixed[]   $options
353
     */
354
    private function getNonAutoincrementPrimaryKeyDefinition(array $columns, array $options) : string
355 1811
    {
356
        if (empty($options['primary'])) {
357 1811
            return '';
358 1376
        }
359
360
        $keyColumns = array_unique(array_values($options['primary']));
361 1783
362
        foreach ($keyColumns as $keyColumn) {
363 1783
            if (! empty($columns[$keyColumn]['autoincrement'])) {
364 1783
                return '';
365 1702
            }
366
        }
367
368
        return ', PRIMARY KEY(' . implode(', ', $keyColumns) . ')';
369 1681
    }
370
371
    /**
372
     * {@inheritDoc}
373
     */
374
    protected function getVarcharTypeDeclarationSQLSnippet(?int $length, bool $fixed) : string
375 1903
    {
376
        return $fixed
377 1903
            ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)')
378 1787
            : ($length ? 'VARCHAR(' . $length . ')' : 'TEXT');
379 1903
    }
380
381
    /**
382
     * {@inheritdoc}
383
     */
384
    protected function getBinaryTypeDeclarationSQLSnippet(?int $length, bool $fixed) : string
385 1496
    {
386
        return 'BLOB';
387 1496
    }
388
389
    /**
390
     * {@inheritdoc}
391
     */
392
    public function getBinaryMaxLength() : int
393 527
    {
394
        return 0;
395 527
    }
396
397
    /**
398
     * {@inheritdoc}
399
     */
400
    public function getBinaryDefaultLength() : int
401 1498
    {
402
        return 0;
403 1498
    }
404
405
    /**
406
     * {@inheritDoc}
407
     */
408
    public function getClobTypeDeclarationSQL(array $field) : string
409 801
    {
410
        return 'CLOB';
411 801
    }
412
413
    /**
414
     * {@inheritDoc}
415
     */
416
    public function getListTableConstraintsSQL(string $table) : string
417 1327
    {
418
        $table = str_replace('.', '__', $table);
419 1327
420
        return sprintf(
421 1327
            "SELECT sql FROM sqlite_master WHERE type='index' AND tbl_name = %s AND sql NOT NULL ORDER BY name",
422 2
            $this->quoteStringLiteral($table)
423 1327
        );
424
    }
425
426
    /**
427
     * {@inheritDoc}
428
     */
429
    public function getListTableColumnsSQL(string $table, ?string $database = null) : string
430 1436
    {
431
        $table = str_replace('.', '__', $table);
432 1436
433
        return sprintf('PRAGMA table_info(%s)', $this->quoteStringLiteral($table));
434 1436
    }
435
436
    /**
437
     * {@inheritDoc}
438
     */
439
    public function getListTableIndexesSQL(string $table, ?string $currentDatabase = null) : string
440 1412
    {
441
        $table = str_replace('.', '__', $table);
442 1412
443
        return sprintf('PRAGMA index_list(%s)', $this->quoteStringLiteral($table));
444 1412
    }
445
446
    /**
447
     * {@inheritDoc}
448
     */
449
    public function getListTablesSQL() : string
450 309
    {
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 309
    }
455
456
    /**
457
     * {@inheritDoc}
458
     */
459
    public function getListViewsSQL(?string $database) : string
460 154
    {
461
        return "SELECT name, sql FROM sqlite_master WHERE type='view' AND sql NOT NULL";
462 154
    }
463
464
    /**
465
     * {@inheritDoc}
466
     */
467
    public function getCreateViewSQL(string $name, string $sql) : string
468 154
    {
469
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
470 154
    }
471
472
    /**
473
     * {@inheritDoc}
474
     */
475
    public function getDropViewSQL(string $name) : string
476 154
    {
477
        return 'DROP VIEW ' . $name;
478 154
    }
479
480
    /**
481
     * {@inheritDoc}
482
     */
483
    public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey) : string
484 1533
    {
485
        $query = parent::getAdvancedForeignKeyOptionsSQL($foreignKey);
486 1533
487
        $query .= ($foreignKey->hasOption('deferrable') && $foreignKey->getOption('deferrable') !== false ? ' ' : ' NOT ') . 'DEFERRABLE';
488 1533
        $query .= ' INITIALLY ' . ($foreignKey->hasOption('deferred') && $foreignKey->getOption('deferred') !== false ? 'DEFERRED' : 'IMMEDIATE');
489 1533
490
        return $query;
491 1533
    }
492
493
    /**
494
     * {@inheritDoc}
495
     */
496
    public function supportsIdentityColumns() : bool
497 153
    {
498
        return true;
499 153
    }
500
501
    /**
502
     * {@inheritDoc}
503
     */
504
    public function supportsColumnCollation() : bool
505 1357
    {
506
        return true;
507 1357
    }
508
509
    /**
510
     * {@inheritDoc}
511
     */
512
    public function supportsInlineColumnComments() : bool
513 1819
    {
514
        return true;
515 1819
    }
516
517
    /**
518
     * {@inheritDoc}
519
     */
520
    public function getName() : string
521 2078
    {
522
        return 'sqlite';
523 2078
    }
524
525
    /**
526
     * {@inheritDoc}
527
     */
528
    public function getTruncateTableSQL(string $tableName, bool $cascade = false) : string
529 816
    {
530
        $tableIdentifier = new Identifier($tableName);
531 816
        $tableName       = str_replace('.', '__', $tableIdentifier->getQuotedName($this));
532 816
533
        return 'DELETE FROM ' . $tableName;
534 816
    }
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
564
        if ($pos !== false) {
565
            return $pos + 1;
566
        }
567
568
        return 0;
569 227
    }
570
571
    /**
572
     * {@inheritDoc}
573 227
     */
574 227
    public function getForUpdateSql() : string
575
    {
576
        return '';
577 227
    }
578
579 227
    /**
580 227
     * {@inheritDoc}
581
     */
582
    public function getInlineColumnCommentSQL(?string $comment) : string
583 227
    {
584
        if ($comment === null || $comment === '') {
585
            return '';
586
        }
587
588
        return '--' . str_replace("\n", "\n--", $comment) . "\n";
589
    }
590
591
    /**
592
     * {@inheritDoc}
593
     */
594
    protected function initializeDoctrineTypeMappings() : void
595
    {
596
        $this->doctrineTypeMapping = [
597 595
            'bigint'           => 'bigint',
598
            'bigserial'        => 'bigint',
599 595
            'blob'             => 'blob',
600
            'boolean'          => 'boolean',
601
            'char'             => 'string',
602
            'clob'             => 'text',
603
            'date'             => 'date',
604
            'datetime'         => 'datetime',
605 1250
            'decimal'          => 'decimal',
606
            'double'           => 'float',
607 1250
            '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
    protected function getReservedKeywordsClass() : string
637
    {
638
        return Keywords\SQLiteKeywords::class;
639
    }
640
641
    /**
642 1250
     * {@inheritDoc}
643
     */
644
    protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff) : array
645
    {
646
        if (! $diff->fromTable instanceof Table) {
647 1839
            throw new DBALException('Sqlite platform requires for alter table the table diff with reference to original table schema.');
648
        }
649 1839
650
        $sql = [];
651
        foreach ($diff->fromTable->getIndexes() as $index) {
652
            if ($index->isPrimary()) {
653
                continue;
654
            }
655 1523
656
            $sql[] = $this->getDropIndexSQL($index, $diff->name);
657 1523
        }
658
659
        return $sql;
660
    }
661 1523
662 1523
    /**
663 1511
     * {@inheritDoc}
664 1507
     */
665
    protected function getPostAlterTableIndexForeignKeySQL(TableDiff $diff) : array
666
    {
667 1505
        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 1523
671
        $sql       = [];
672
        $tableName = $diff->getNewName();
673
674
        if ($tableName === false) {
675
            $tableName = $diff->getName($this);
676 1523
        }
677
678 1523
        foreach ($this->getIndexesInAlteredTable($diff) as $index) {
679
            if ($index->isPrimary()) {
680
                continue;
681
            }
682 1523
683 1523
            $sql[] = $this->getCreateIndexSQL($index, $tableName->getQuotedName($this));
684
        }
685 1523
686 941
        return $sql;
687
    }
688
689 1523
    /**
690 1511
     * {@inheritDoc}
691 1507
     */
692
    protected function doModifyLimitQuery(string $query, ?int $limit, int $offset) : string
693
    {
694 1509
        if ($limit === null && $offset > 0) {
695
            $limit = -1;
696
        }
697 1523
698
        return parent::doModifyLimitQuery($query, $limit, $offset);
699
    }
700
701
    /**
702
     * {@inheritDoc}
703 1734
     */
704
    public function getBlobTypeDeclarationSQL(array $field) : string
705 1734
    {
706 1704
        return 'BLOB';
707
    }
708
709 1734
    /**
710
     * {@inheritDoc}
711
     */
712
    public function getTemporaryTableName(string $tableName) : string
713
    {
714
        $tableName = str_replace('.', '__', $tableName);
715 295
716
        return $tableName;
717 295
    }
718
719
    /**
720
     * {@inheritDoc}
721
     *
722
     * Sqlite Platform emulates schema by underscoring each dot and generating tables
723 108
     * into the default database.
724
     *
725 108
     * This hack is implemented to be able to use SQLite as testdriver when
726
     * using schema supporting databases.
727 108
     */
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
    /**
742
     * {@inheritDoc}
743
     */
744
    public function getCreatePrimaryKeySQL(Index $index, $table) : string
745
    {
746
        throw new DBALException('Sqlite platform does not support alter primary key.');
747 1607
    }
748
749 1607
    /**
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
    /**
758
     * {@inheritdoc}
759
     */
760
    public function getDropForeignKeySQL($foreignKey, $table) : string
761
    {
762
        throw new DBALException('Sqlite platform does not support alter foreign key.');
763 1629
    }
764
765 1629
    /**
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
    /**
774
     * {@inheritDoc}
775
     */
776
    public function getCreateTableSQL(Table $table, int $createFlags = self::CREATE_INDEXES | self::CREATE_FOREIGNKEYS) : array
777
    {
778
        return parent::getCreateTableSQL($table, $createFlags);
779 1602
    }
780
781 1602
    /**
782
     * {@inheritDoc}
783
     */
784
    public function getListTableForeignKeysSQL(string $table, ?string $database = null) : string
785
    {
786
        $table = str_replace('.', '__', $table);
787 1813
788
        return sprintf('PRAGMA foreign_key_list(%s)', $this->quoteStringLiteral($table));
789 1813
    }
790
791 1813
    /**
792
     * {@inheritDoc}
793
     */
794
    public function getAlterTableSQL(TableDiff $diff) : array
795
    {
796
        $sql = $this->getSimpleAlterTableSQL($diff);
797 1402
        if ($sql !== false) {
0 ignored issues
show
introduced by
The condition $sql !== false is always false.
Loading history...
798
            return $sql;
799 1402
        }
800
801 1402
        $fromTable = $diff->fromTable;
802
        if (! $fromTable instanceof Table) {
803
            throw new DBALException('Sqlite platform requires for alter table the table diff with reference to original table schema.');
804
        }
805
806
        $table = clone $fromTable;
807 1647
808
        $columns        = [];
809 1647
        $oldColumnNames = [];
810 1647
        $newColumnNames = [];
811 1619
        $columnSql      = [];
812
813
        foreach ($table->getColumns() as $columnName => $column) {
814 1599
            $columnName                  = strtolower($columnName);
815 1599
            $columns[$columnName]        = $column;
816 1479
            $oldColumnNames[$columnName] = $newColumnNames[$columnName] = $column->getQuotedName($this);
817
        }
818
819 1523
        foreach ($diff->removedColumns as $columnName => $column) {
820
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
821 1523
                continue;
822 1523
            }
823 1523
824 1523
            $columnName = strtolower($columnName);
825
            if (! isset($columns[$columnName])) {
826 1523
                continue;
827 1521
            }
828 1521
829 1521
            unset(
830
                $columns[$columnName],
831
                $oldColumnNames[$columnName],
832 1523
                $newColumnNames[$columnName]
833 1507
            );
834
        }
835
836
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
837 1507
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
838 1507
                continue;
839
            }
840
841
            $oldColumnName = strtolower($oldColumnName);
842
            if (isset($columns[$oldColumnName])) {
843 1507
                unset($columns[$oldColumnName]);
844 1507
            }
845 1507
846
            $columns[strtolower($column->getName())] = $column;
847
848
            if (! isset($newColumnNames[$oldColumnName])) {
849 1523
                continue;
850 1410
            }
851
852
            $newColumnNames[$oldColumnName] = $column->getQuotedName($this);
853
        }
854 1410
855 1410
        foreach ($diff->changedColumns as $oldColumnName => $columnDiff) {
856 1410
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
857
                continue;
858
            }
859 1410
860
            if (isset($columns[$oldColumnName])) {
861 1410
                unset($columns[$oldColumnName]);
862
            }
863
864
            $columns[strtolower($columnDiff->column->getName())] = $columnDiff->column;
865 1410
866
            if (! isset($newColumnNames[$oldColumnName])) {
867
                continue;
868 1523
            }
869 979
870
            $newColumnNames[$oldColumnName] = $columnDiff->column->getQuotedName($this);
871
        }
872
873 979
        foreach ($diff->addedColumns as $columnName => $column) {
874 977
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
875
                continue;
876
            }
877 979
878
            $columns[strtolower($columnName)] = $column;
879 979
        }
880 577
881
        $sql      = [];
882
        $tableSql = [];
883 977
884
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
885
            $dataTable = new Table('__temp__' . $table->getName());
886 1523
887 977
            $newTable = new Table($table->getQuotedName($this), $columns, $this->getPrimaryIndexInAlteredTable($diff), [], $this->getForeignKeysInAlteredTable($diff), $table->getOptions());
888
            $newTable->addOption('alter', true);
889
890
            $sql = $this->getPreAlterTableIndexForeignKeySQL($diff);
891 977
            //$sql = array_merge($sql, $this->getCreateTableSQL($dataTable, 0));
892
            $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 1523
895 1523
            $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 1523
            $sql[] = $this->getDropTableSQL($dataTable);
898 1523
899
            $newName = $diff->getNewName();
900 1523
901 1523
            if ($newName !== false) {
902
                $sql[] = sprintf(
903 1523
                    'ALTER TABLE %s RENAME TO %s',
904
                    $newTable->getQuotedName($this),
905 1523
                    $newName->getQuotedName($this)
906 1523
                );
907
            }
908 1523
909 1523
            $sql = array_merge($sql, $this->getPostAlterTableIndexForeignKeySQL($diff));
910 1523
        }
911
912 1523
        return array_merge($sql, $tableSql, $columnSql);
913
    }
914 1523
915 1406
    /**
916 6
     * @return string[]|false
917 1406
     */
918 1406
    private function getSimpleAlterTableSQL(TableDiff $diff)
919
    {
920
        // Suppress changes on integer type autoincrement columns.
921
        foreach ($diff->changedColumns as $oldColumnName => $columnDiff) {
922 1523
            if (! $columnDiff->fromColumn instanceof Column ||
923
                ! $columnDiff->column instanceof Column ||
924
                ! $columnDiff->column->getAutoincrement() ||
925 1523
                ! $columnDiff->column->getType() instanceof Types\IntegerType
926
            ) {
927
                continue;
928
            }
929
930
            if (! $columnDiff->hasChanged('type') && $columnDiff->hasChanged('unsigned')) {
931 1647
                unset($diff->changedColumns[$oldColumnName]);
932
933
                continue;
934 1647
            }
935 999
936 991
            $fromColumnType = $columnDiff->fromColumn->getType();
937 991
938 999
            if (! ($fromColumnType instanceof Types\SmallIntType) && ! ($fromColumnType instanceof Types\BigIntType)) {
939
                continue;
940 979
            }
941
942
            unset($diff->changedColumns[$oldColumnName]);
943 171
        }
944 168
945
        if (! empty($diff->renamedColumns) || ! empty($diff->addedForeignKeys) || ! empty($diff->addedIndexes)
946 168
                || ! empty($diff->changedColumns) || ! empty($diff->changedForeignKeys) || ! empty($diff->changedIndexes)
947
                || ! empty($diff->removedColumns) || ! empty($diff->removedForeignKeys) || ! empty($diff->removedIndexes)
948
                || ! empty($diff->renamedIndexes)
949 171
        ) {
950
            return false;
951 171
        }
952
953
        $table = new Table($diff->name);
954
955 171
        $sql       = [];
956
        $tableSql  = [];
957
        $columnSql = [];
958 1647
959 1637
        foreach ($diff->addedColumns as $column) {
960 1629
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
961 1647
                continue;
962
            }
963 1523
964
            $field = array_merge(['unique' => null, 'autoincrement' => null, 'default' => null], $column->toArray());
965
            $type  = $field['type'];
966 1623
            switch (true) {
967
                case isset($field['columnDefinition']) || $field['autoincrement'] || $field['unique']:
968 1623
                case $type instanceof Types\DateTimeType && $field['default'] === $this->getCurrentTimestampSQL():
969 1623
                case $type instanceof Types\DateType && $field['default'] === $this->getCurrentDateSQL():
970 1623
                case $type instanceof Types\TimeType && $field['default'] === $this->getCurrentTimeSQL():
971
                    return false;
972 1623
            }
973 1506
974
            $field['name'] = $column->getQuotedName($this);
975
            if ($type instanceof Types\StringType && $field['length'] === null) {
976
                $field['length'] = 255;
977 1506
            }
978 1506
979
            $sql[] = 'ALTER TABLE ' . $table->getQuotedName($this) . ' ADD COLUMN ' . $this->getColumnDeclarationSQL($field['name'], $field);
980 1506
        }
981 1504
982 1504
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
983 1502
            if ($diff->newName !== false) {
984 1479
                $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
            }
987 1502
        }
988 1502
989 1502
        return array_merge($sql, $tableSql, $columnSql);
990
    }
991
992 1502
    /**
993
     * @return string[]
994
     */
995 1619
    private function getColumnNamesInAlteredTable(TableDiff $diff) : array
996 1619
    {
997 177
        $columns = [];
998 177
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 1619
1003
        foreach ($diff->removedColumns as $columnName => $column) {
1004
            $columnName = strtolower($columnName);
1005
            if (! isset($columns[$columnName])) {
1006
                continue;
1007
            }
1008 1523
1009
            unset($columns[$columnName]);
1010 1523
        }
1011
1012 1523
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
1013 1521
            $columnName                          = $column->getName();
1014
            $columns[strtolower($oldColumnName)] = $columnName;
1015
            $columns[strtolower($columnName)]    = $columnName;
1016 1523
        }
1017 1507
1018 1507
        foreach ($diff->changedColumns as $oldColumnName => $columnDiff) {
1019
            $columnName                          = $columnDiff->column->getName();
1020
            $columns[strtolower($oldColumnName)] = $columnName;
1021
            $columns[strtolower($columnName)]    = $columnName;
1022 1507
        }
1023
1024
        foreach ($diff->addedColumns as $column) {
1025 1523
            $columnName                       = $column->getName();
1026 1410
            $columns[strtolower($columnName)] = $columnName;
1027 1410
        }
1028 1410
1029
        return $columns;
1030
    }
1031 1523
1032 979
    /**
1033 979
     * @return Index[]
1034 979
     */
1035
    private function getIndexesInAlteredTable(TableDiff $diff) : array
1036
    {
1037 1523
        $indexes     = $diff->fromTable->getIndexes();
1038 977
        $columnNames = $this->getColumnNamesInAlteredTable($diff);
1039 977
1040
        foreach ($indexes as $key => $index) {
1041
            foreach ($diff->renamedIndexes as $oldIndexName => $renamedIndex) {
1042 1523
                if (strtolower($key) !== strtolower($oldIndexName)) {
1043
                    continue;
1044
                }
1045
1046
                unset($indexes[$key]);
1047
            }
1048 1523
1049
            $changed      = false;
1050 1523
            $indexColumns = [];
1051 1523
            foreach ($index->getColumns() as $columnName) {
1052
                $normalizedColumnName = strtolower($columnName);
1053 1523
                if (! isset($columnNames[$normalizedColumnName])) {
1054 1511
                    unset($indexes[$key]);
1055 641
                    continue 2;
1056 641
                }
1057
1058
                $indexColumns[] = $columnNames[$normalizedColumnName];
1059 349
                if ($columnName === $columnNames[$normalizedColumnName]) {
1060
                    continue;
1061
                }
1062 1511
1063 1511
                $changed = true;
1064 1511
            }
1065 1511
1066 1511
            if (! $changed) {
1067 1402
                continue;
1068 1402
            }
1069
1070
            $indexes[$key] = new Index($index->getName(), $indexColumns, $index->isUnique(), $index->isPrimary(), $index->getFlags());
1071 1511
        }
1072 1511
1073 1511
        foreach ($diff->removedIndexes as $index) {
1074
            $indexName = $index->getName();
1075
1076 1402
            if ($indexName === null) {
1077
                continue;
1078
            }
1079 1511
1080 1511
            unset($indexes[strtolower($indexName)]);
1081
        }
1082
1083 1402
        foreach (array_merge($diff->changedIndexes, $diff->addedIndexes, $diff->renamedIndexes) as $index) {
1084
            $indexName = $index->getName();
1085
1086 1523
            if ($indexName !== null) {
1087 1501
                $indexes[strtolower($indexName)] = $index;
1088 1501
            } else {
1089
                $indexes[] = $index;
1090
            }
1091
        }
1092 1501
1093
        return $indexes;
1094
    }
1095 1523
1096 641
    /**
1097 641
     * @return ForeignKeyConstraint[]
1098 641
     */
1099
    private function getForeignKeysInAlteredTable(TableDiff $diff) : array
1100 6
    {
1101
        $foreignKeys = $diff->fromTable->getForeignKeys();
1102
        $columnNames = $this->getColumnNamesInAlteredTable($diff);
1103
1104 1523
        foreach ($foreignKeys as $key => $constraint) {
1105
            $changed      = false;
1106
            $localColumns = [];
1107
            foreach ($constraint->getLocalColumns() as $columnName) {
1108
                $normalizedColumnName = strtolower($columnName);
1109
                if (! isset($columnNames[$normalizedColumnName])) {
1110 1523
                    unset($foreignKeys[$key]);
1111
                    continue 2;
1112 1523
                }
1113 1523
1114
                $localColumns[] = $columnNames[$normalizedColumnName];
1115 1523
                if ($columnName === $columnNames[$normalizedColumnName]) {
1116 1406
                    continue;
1117 1406
                }
1118 1406
1119 1406
                $changed = true;
1120 1406
            }
1121 1402
1122 1402
            if (! $changed) {
1123
                continue;
1124
            }
1125 1406
1126 1406
            $foreignKeys[$key] = new ForeignKeyConstraint($localColumns, $constraint->getForeignTableName(), $constraint->getForeignColumns(), $constraint->getName(), $constraint->getOptions());
1127 1406
        }
1128
1129
        foreach ($diff->removedForeignKeys as $constraint) {
1130 1402
            if (! $constraint instanceof ForeignKeyConstraint) {
1131
                $constraint = new Identifier($constraint);
1132
            }
1133 1406
1134 1406
            $constraintName = $constraint->getName();
1135
1136
            if ($constraintName === null) {
1137 1402
                continue;
1138
            }
1139
1140 1523
            unset($foreignKeys[strtolower($constraintName)]);
1141 252
        }
1142
1143
        foreach (array_merge($diff->changedForeignKeys, $diff->addedForeignKeys) as $constraint) {
1144
            $constraintName = $constraint->getName();
1145 252
1146 252
            if ($constraintName !== null) {
1147
                $foreignKeys[strtolower($constraintName)] = $constraint;
1148
            } else {
1149
                $foreignKeys[] = $constraint;
1150 252
            }
1151
        }
1152
1153 1523
        return $foreignKeys;
1154 397
    }
1155 397
1156 252
    /**
1157
     * @return Index[]
1158 157
     */
1159
    private function getPrimaryIndexInAlteredTable(TableDiff $diff) : array
1160
    {
1161
        $primaryIndex = [];
1162 1523
1163
        foreach ($this->getIndexesInAlteredTable($diff) as $index) {
1164
            if (! $index->isPrimary()) {
1165
                continue;
1166
            }
1167
1168 1523
            $primaryIndex = [$index->getName() => $index];
1169
        }
1170 1523
1171
        return $primaryIndex;
1172 1523
    }
1173
}
1174