Completed
Push — master ( 1a9812...b70610 )
by Sergei
19s queued 14s
created

SqlitePlatform::getForeignKeysInAlteredTable()   B

Complexity

Conditions 11
Paths 120

Size

Total Lines 55
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 29
CRAP Score 11.0324

Importance

Changes 0
Metric Value
eloc 31
dl 0
loc 55
ccs 29
cts 31
cp 0.9355
rs 7.15
c 0
b 0
f 0
cc 11
nc 120
nop 1
crap 11.0324

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

1023
        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...
1024 310
            $columns[strtolower($columnName)] = $column->getName();
1025
        }
1026
1027 337
        foreach ($diff->removedColumns as $columnName => $column) {
1028 109
            $columnName = strtolower($columnName);
1029 109
            if (! isset($columns[$columnName])) {
1030
                continue;
1031
            }
1032
1033 109
            unset($columns[$columnName]);
1034
        }
1035
1036 337
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
1037 135
            $columnName                          = $column->getName();
1038 135
            $columns[strtolower($oldColumnName)] = $columnName;
1039 135
            $columns[strtolower($columnName)]    = $columnName;
1040
        }
1041
1042 337
        foreach ($diff->changedColumns as $oldColumnName => $columnDiff) {
1043 174
            $columnName                          = $columnDiff->column->getName();
1044 174
            $columns[strtolower($oldColumnName)] = $columnName;
1045 174
            $columns[strtolower($columnName)]    = $columnName;
1046
        }
1047
1048 337
        foreach ($diff->addedColumns as $column) {
1049 82
            $columnName                       = $column->getName();
1050 82
            $columns[strtolower($columnName)] = $columnName;
1051
        }
1052
1053 337
        return $columns;
1054
    }
1055
1056
    /**
1057
     * @return Index[]
1058
     */
1059 337
    private function getIndexesInAlteredTable(TableDiff $diff) : array
1060
    {
1061 337
        $indexes     = $diff->fromTable->getIndexes();
1062 337
        $columnNames = $this->getColumnNamesInAlteredTable($diff);
1063
1064 337
        foreach ($indexes as $key => $index) {
1065 165
            foreach ($diff->renamedIndexes as $oldIndexName => $renamedIndex) {
1066 82
                if (strtolower($key) !== strtolower($oldIndexName)) {
1067 82
                    continue;
1068
                }
1069
1070 28
                unset($indexes[$key]);
1071
            }
1072
1073 165
            $changed      = false;
1074 165
            $indexColumns = [];
1075 165
            foreach ($index->getColumns() as $columnName) {
1076 165
                $normalizedColumnName = strtolower($columnName);
1077 165
                if (! isset($columnNames[$normalizedColumnName])) {
1078 27
                    unset($indexes[$key]);
1079 27
                    continue 2;
1080
                }
1081
1082 165
                $indexColumns[] = $columnNames[$normalizedColumnName];
1083 165
                if ($columnName === $columnNames[$normalizedColumnName]) {
1084 165
                    continue;
1085
                }
1086
1087 27
                $changed = true;
1088
            }
1089
1090 165
            if (! $changed) {
1091 165
                continue;
1092
            }
1093
1094 27
            $indexes[$key] = new Index($index->getName(), $indexColumns, $index->isUnique(), $index->isPrimary(), $index->getFlags());
1095
        }
1096
1097 337
        foreach ($diff->removedIndexes as $index) {
1098 28
            $indexName = $index->getName();
1099
1100 28
            if ($indexName === '') {
1101
                continue;
1102
            }
1103
1104 28
            unset($indexes[strtolower($indexName)]);
1105
        }
1106
1107 337
        foreach (array_merge($diff->changedIndexes, $diff->addedIndexes, $diff->renamedIndexes) as $index) {
1108 82
            $indexName = $index->getName();
1109
1110 82
            if ($indexName !== '') {
1111 82
                $indexes[strtolower($indexName)] = $index;
1112
            } else {
1113
                $indexes[] = $index;
1114
            }
1115
        }
1116
1117 337
        return $indexes;
1118
    }
1119
1120
    /**
1121
     * @return ForeignKeyConstraint[]
1122
     */
1123 337
    private function getForeignKeysInAlteredTable(TableDiff $diff) : array
1124
    {
1125 337
        $foreignKeys = $diff->fromTable->getForeignKeys();
1126 337
        $columnNames = $this->getColumnNamesInAlteredTable($diff);
1127
1128 337
        foreach ($foreignKeys as $key => $constraint) {
1129 81
            $changed      = false;
1130 81
            $localColumns = [];
1131 81
            foreach ($constraint->getLocalColumns() as $columnName) {
1132 81
                $normalizedColumnName = strtolower($columnName);
1133 81
                if (! isset($columnNames[$normalizedColumnName])) {
1134 27
                    unset($foreignKeys[$key]);
1135 27
                    continue 2;
1136
                }
1137
1138 81
                $localColumns[] = $columnNames[$normalizedColumnName];
1139 81
                if ($columnName === $columnNames[$normalizedColumnName]) {
1140 81
                    continue;
1141
                }
1142
1143 27
                $changed = true;
1144
            }
1145
1146 81
            if (! $changed) {
1147 81
                continue;
1148
            }
1149
1150 27
            $foreignKeys[$key] = new ForeignKeyConstraint($localColumns, $constraint->getForeignTableName(), $constraint->getForeignColumns(), $constraint->getName(), $constraint->getOptions());
1151
        }
1152
1153 337
        foreach ($diff->removedForeignKeys as $constraint) {
1154 27
            if (! $constraint instanceof ForeignKeyConstraint) {
1155
                $constraint = new Identifier($constraint);
1156
            }
1157
1158 27
            $constraintName = $constraint->getName();
1159
1160 27
            if ($constraintName === '') {
1161
                continue;
1162
            }
1163
1164 27
            unset($foreignKeys[strtolower($constraintName)]);
1165
        }
1166
1167 337
        foreach (array_merge($diff->changedForeignKeys, $diff->addedForeignKeys) as $constraint) {
1168 28
            $constraintName = $constraint->getName();
1169
1170 28
            if ($constraintName !== '') {
1171 27
                $foreignKeys[strtolower($constraintName)] = $constraint;
1172
            } else {
1173 1
                $foreignKeys[] = $constraint;
1174
            }
1175
        }
1176
1177 337
        return $foreignKeys;
1178
    }
1179
1180
    /**
1181
     * @return Index[]
1182
     */
1183 337
    private function getPrimaryIndexInAlteredTable(TableDiff $diff) : array
1184
    {
1185 337
        $primaryIndex = [];
1186
1187 337
        foreach ($this->getIndexesInAlteredTable($diff) as $index) {
1188 165
            if (! $index->isPrimary()) {
1189 136
                continue;
1190
            }
1191
1192 111
            $primaryIndex = [$index->getName() => $index];
1193
        }
1194
1195 337
        return $primaryIndex;
1196
    }
1197
}
1198