Failed Conditions
Push — develop ( c067f0...c4478a )
by Sergei
10:16
created

SqlitePlatform::getColumnNamesInAlteredTable()   B

Complexity

Conditions 7
Paths 48

Size

Total Lines 34
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 7.0061

Importance

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

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

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

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

Loading history...
787
    {
788 21
        $table = str_replace('.', '__', $table);
789
790 21
        return sprintf('PRAGMA foreign_key_list(%s)', $this->quoteStringLiteral($table));
791
    }
792
793
    /**
794
     * {@inheritDoc}
795
     */
796 323
    public function getAlterTableSQL(TableDiff $diff)
797
    {
798 323
        $sql = $this->getSimpleAlterTableSQL($diff);
799 323
        if ($sql !== false) {
0 ignored issues
show
introduced by
The condition $sql !== false is always false.
Loading history...
800 31
            return $sql;
801
        }
802
803 292
        $fromTable = $diff->fromTable;
804 292
        if (! $fromTable instanceof Table) {
0 ignored issues
show
introduced by
$fromTable is always a sub-type of Doctrine\DBAL\Schema\Table. If $fromTable can have other possible types, add them to lib/Doctrine/DBAL/Schema/TableDiff.php:97.
Loading history...
805 38
            throw new DBALException('Sqlite platform requires for alter table the table diff with reference to original table schema');
806
        }
807
808 254
        $table = clone $fromTable;
809
810 254
        $columns        = [];
811 254
        $oldColumnNames = [];
812 254
        $newColumnNames = [];
813 254
        $columnSql      = [];
814
815 254
        foreach ($table->getColumns() as $columnName => $column) {
816 235
            $columnName                  = strtolower($columnName);
817 235
            $columns[$columnName]        = $column;
818 235
            $oldColumnNames[$columnName] = $newColumnNames[$columnName] = $column->getQuotedName($this);
819
        }
820
821 254
        foreach ($diff->removedColumns as $columnName => $column) {
822 78
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
823
                continue;
824
            }
825
826 78
            $columnName = strtolower($columnName);
827 78
            if (! isset($columns[$columnName])) {
828
                continue;
829
            }
830
831
            unset(
832 78
                $columns[$columnName],
833 78
                $oldColumnNames[$columnName],
834 78
                $newColumnNames[$columnName]
835
            );
836
        }
837
838 254
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
839 95
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
840
                continue;
841
            }
842
843 95
            $oldColumnName = strtolower($oldColumnName);
844 95
            if (isset($columns[$oldColumnName])) {
845 95
                unset($columns[$oldColumnName]);
846
            }
847
848 95
            $columns[strtolower($column->getName())] = $column;
849
850 95
            if (! isset($newColumnNames[$oldColumnName])) {
851
                continue;
852
            }
853
854 95
            $newColumnNames[$oldColumnName] = $column->getQuotedName($this);
855
        }
856
857 254
        foreach ($diff->changedColumns as $oldColumnName => $columnDiff) {
858 138
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
859
                continue;
860
            }
861
862 138
            if (isset($columns[$oldColumnName])) {
863 119
                unset($columns[$oldColumnName]);
864
            }
865
866 138
            $columns[strtolower($columnDiff->column->getName())] = $columnDiff->column;
867
868 138
            if (! isset($newColumnNames[$oldColumnName])) {
869 19
                continue;
870
            }
871
872 119
            $newColumnNames[$oldColumnName] = $columnDiff->column->getQuotedName($this);
873
        }
874
875 254
        foreach ($diff->addedColumns as $columnName => $column) {
876 59
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
877
                continue;
878
            }
879
880 59
            $columns[strtolower($columnName)] = $column;
881
        }
882
883 254
        $sql      = [];
884 254
        $tableSql = [];
885
886 254
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
887 254
            $dataTable = new Table('__temp__' . $table->getName());
888
889 254
            $newTable = new Table($table->getQuotedName($this), $columns, $this->getPrimaryIndexInAlteredTable($diff), [], $this->getForeignKeysInAlteredTable($diff), $table->getOptions());
890 254
            $newTable->addOption('alter', true);
0 ignored issues
show
Bug introduced by
true of type true is incompatible with the type string expected by parameter $value of Doctrine\DBAL\Schema\Table::addOption(). ( Ignorable by Annotation )

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

890
            $newTable->addOption('alter', /** @scrutinizer ignore-type */ true);
Loading history...
891
892 254
            $sql = $this->getPreAlterTableIndexForeignKeySQL($diff);
893
            //$sql = array_merge($sql, $this->getCreateTableSQL($dataTable, 0));
894 254
            $sql[] = sprintf('CREATE TEMPORARY TABLE %s AS SELECT %s FROM %s', $dataTable->getQuotedName($this), implode(', ', $oldColumnNames), $table->getQuotedName($this));
895 254
            $sql[] = $this->getDropTableSQL($fromTable);
896
897 254
            $sql   = array_merge($sql, $this->getCreateTableSQL($newTable));
898 254
            $sql[] = sprintf('INSERT INTO %s (%s) SELECT %s FROM %s', $newTable->getQuotedName($this), implode(', ', $newColumnNames), implode(', ', $oldColumnNames), $dataTable->getQuotedName($this));
899 254
            $sql[] = $this->getDropTableSQL($dataTable);
900
901 254
            if ($diff->newName && $diff->newName !== $diff->name) {
902 57
                $renamedTable = $diff->getNewName();
903 57
                $sql[]        = 'ALTER TABLE ' . $newTable->getQuotedName($this) . ' RENAME TO ' . $renamedTable->getQuotedName($this);
904
            }
905
906 254
            $sql = array_merge($sql, $this->getPostAlterTableIndexForeignKeySQL($diff));
907
        }
908
909 254
        return array_merge($sql, $tableSql, $columnSql);
910
    }
911
912
    /**
913
     * @return string[]|false
914
     */
915 323
    private function getSimpleAlterTableSQL(TableDiff $diff)
916
    {
917
        // Suppress changes on integer type autoincrement columns.
918 323
        foreach ($diff->changedColumns as $oldColumnName => $columnDiff) {
919 148
            if (! $columnDiff->fromColumn instanceof Column ||
920 72
                ! $columnDiff->column instanceof Column ||
921 72
                ! $columnDiff->column->getAutoincrement() ||
922 148
                ! $columnDiff->column->getType() instanceof Types\IntegerType
923
            ) {
924 138
                continue;
925
            }
926
927 10
            if (! $columnDiff->hasChanged('type') && $columnDiff->hasChanged('unsigned')) {
928 2
                unset($diff->changedColumns[$oldColumnName]);
929
930 2
                continue;
931
            }
932
933 8
            $fromColumnType = $columnDiff->fromColumn->getType();
934
935 8
            if (! ($fromColumnType instanceof Types\SmallIntType) && ! ($fromColumnType instanceof Types\BigIntType)) {
936
                continue;
937
            }
938
939 8
            unset($diff->changedColumns[$oldColumnName]);
940
        }
941
942 323
        if (! empty($diff->renamedColumns) || ! empty($diff->addedForeignKeys) || ! empty($diff->addedIndexes)
943 228
                || ! empty($diff->changedColumns) || ! empty($diff->changedForeignKeys) || ! empty($diff->changedIndexes)
944 128
                || ! empty($diff->removedColumns) || ! empty($diff->removedForeignKeys) || ! empty($diff->removedIndexes)
945 323
                || ! empty($diff->renamedIndexes)
946
        ) {
947 254
            return false;
948
        }
949
950 69
        $table = new Table($diff->name);
951
952 69
        $sql       = [];
953 69
        $tableSql  = [];
954 69
        $columnSql = [];
955
956 69
        foreach ($diff->addedColumns as $column) {
957 57
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
958
                continue;
959
            }
960
961 57
            $field = array_merge(['unique' => null, 'autoincrement' => null, 'default' => null], $column->toArray());
962 57
            $type  = $field['type'];
963
            switch (true) {
964 57
                case isset($field['columnDefinition']) || $field['autoincrement'] || $field['unique']:
965 38
                case $type instanceof Types\DateTimeType && $field['default'] === $this->getCurrentTimestampSQL():
966 38
                case $type instanceof Types\DateType && $field['default'] === $this->getCurrentDateSQL():
967 19
                case $type instanceof Types\TimeType && $field['default'] === $this->getCurrentTimeSQL():
968 38
                    return false;
969
            }
970
971 19
            $field['name'] = $column->getQuotedName($this);
972 19
            if ($type instanceof Types\StringType && $field['length'] === null) {
973 19
                $field['length'] = 255;
974
            }
975
976 19
            $sql[] = 'ALTER TABLE ' . $table->getQuotedName($this) . ' ADD COLUMN ' . $this->getColumnDeclarationSQL($field['name'], $field);
977
        }
978
979 31
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
980 31
            if ($diff->newName !== false) {
981 2
                $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

981
                $newTable = new Identifier(/** @scrutinizer ignore-type */ $diff->newName);
Loading history...
982 2
                $sql[]    = 'ALTER TABLE ' . $table->getQuotedName($this) . ' RENAME TO ' . $newTable->getQuotedName($this);
983
            }
984
        }
985
986 31
        return array_merge($sql, $tableSql, $columnSql);
987
    }
988
989
    /**
990
     * @return string[]
991
     */
992 254
    private function getColumnNamesInAlteredTable(TableDiff $diff)
993
    {
994 254
        $columns = [];
995
996 254
        foreach ($diff->fromTable->getColumns() as $columnName => $column) {
997 235
            $columns[strtolower($columnName)] = $column->getName();
998
        }
999
1000 254
        foreach ($diff->removedColumns as $columnName => $column) {
1001 78
            $columnName = strtolower($columnName);
1002 78
            if (! isset($columns[$columnName])) {
1003
                continue;
1004
            }
1005
1006 78
            unset($columns[$columnName]);
1007
        }
1008
1009 254
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
1010 95
            $columnName                          = $column->getName();
1011 95
            $columns[strtolower($oldColumnName)] = $columnName;
1012 95
            $columns[strtolower($columnName)]    = $columnName;
1013
        }
1014
1015 254
        foreach ($diff->changedColumns as $oldColumnName => $columnDiff) {
1016 138
            $columnName                          = $columnDiff->column->getName();
1017 138
            $columns[strtolower($oldColumnName)] = $columnName;
1018 138
            $columns[strtolower($columnName)]    = $columnName;
1019
        }
1020
1021 254
        foreach ($diff->addedColumns as $columnName => $column) {
1022 59
            $columns[strtolower($columnName)] = $columnName;
1023
        }
1024
1025 254
        return $columns;
1026
    }
1027
1028
    /**
1029
     * @return Index[]
1030
     */
1031 254
    private function getIndexesInAlteredTable(TableDiff $diff)
1032
    {
1033 254
        $indexes     = $diff->fromTable->getIndexes();
1034 254
        $columnNames = $this->getColumnNamesInAlteredTable($diff);
1035
1036 254
        foreach ($indexes as $key => $index) {
1037 120
            foreach ($diff->renamedIndexes as $oldIndexName => $renamedIndex) {
1038 59
                if (strtolower($key) !== strtolower($oldIndexName)) {
1039 59
                    continue;
1040
                }
1041
1042 21
                unset($indexes[$key]);
1043
            }
1044
1045 120
            $changed      = false;
1046 120
            $indexColumns = [];
1047 120
            foreach ($index->getColumns() as $columnName) {
1048 120
                $normalizedColumnName = strtolower($columnName);
1049 120
                if (! isset($columnNames[$normalizedColumnName])) {
1050 19
                    unset($indexes[$key]);
1051 19
                    continue 2;
1052
                } else {
1053 120
                    $indexColumns[] = $columnNames[$normalizedColumnName];
1054 120
                    if ($columnName !== $columnNames[$normalizedColumnName]) {
1055 120
                        $changed = true;
1056
                    }
1057
                }
1058
            }
1059
1060 120
            if (! $changed) {
1061 120
                continue;
1062
            }
1063
1064 19
            $indexes[$key] = new Index($index->getName(), $indexColumns, $index->isUnique(), $index->isPrimary(), $index->getFlags());
1065
        }
1066
1067 254
        foreach ($diff->removedIndexes as $index) {
1068 21
            $indexName = strtolower($index->getName());
1069 21
            if (! strlen($indexName) || ! isset($indexes[$indexName])) {
1070
                continue;
1071
            }
1072
1073 21
            unset($indexes[$indexName]);
1074
        }
1075
1076 254
        foreach (array_merge($diff->changedIndexes, $diff->addedIndexes, $diff->renamedIndexes) as $index) {
1077 59
            $indexName = strtolower($index->getName());
1078 59
            if (strlen($indexName)) {
1079 59
                $indexes[$indexName] = $index;
1080
            } else {
1081 59
                $indexes[] = $index;
1082
            }
1083
        }
1084
1085 254
        return $indexes;
1086
    }
1087
1088
    /**
1089
     * @return ForeignKeyConstraint[]
1090
     */
1091 254
    private function getForeignKeysInAlteredTable(TableDiff $diff)
1092
    {
1093 254
        $foreignKeys = $diff->fromTable->getForeignKeys();
1094 254
        $columnNames = $this->getColumnNamesInAlteredTable($diff);
1095
1096 254
        foreach ($foreignKeys as $key => $constraint) {
1097 57
            $changed      = false;
1098 57
            $localColumns = [];
1099 57
            foreach ($constraint->getLocalColumns() as $columnName) {
1100 57
                $normalizedColumnName = strtolower($columnName);
1101 57
                if (! isset($columnNames[$normalizedColumnName])) {
1102 19
                    unset($foreignKeys[$key]);
1103 19
                    continue 2;
1104
                } else {
1105 57
                    $localColumns[] = $columnNames[$normalizedColumnName];
1106 57
                    if ($columnName !== $columnNames[$normalizedColumnName]) {
1107 57
                        $changed = true;
1108
                    }
1109
                }
1110
            }
1111
1112 57
            if (! $changed) {
1113 57
                continue;
1114
            }
1115
1116 19
            $foreignKeys[$key] = new ForeignKeyConstraint($localColumns, $constraint->getForeignTableName(), $constraint->getForeignColumns(), $constraint->getName(), $constraint->getOptions());
1117
        }
1118
1119 254
        foreach ($diff->removedForeignKeys as $constraint) {
1120 19
            $constraintName = strtolower($constraint->getName());
1121 19
            if (! strlen($constraintName) || ! isset($foreignKeys[$constraintName])) {
1122
                continue;
1123
            }
1124
1125 19
            unset($foreignKeys[$constraintName]);
1126
        }
1127
1128 254
        foreach (array_merge($diff->changedForeignKeys, $diff->addedForeignKeys) as $constraint) {
1129 21
            $constraintName = strtolower($constraint->getName());
1130 21
            if (strlen($constraintName)) {
1131 19
                $foreignKeys[$constraintName] = $constraint;
1132
            } else {
1133 21
                $foreignKeys[] = $constraint;
1134
            }
1135
        }
1136
1137 254
        return $foreignKeys;
1138
    }
1139
1140
    /**
1141
     * @return Index[]
1142
     */
1143 254
    private function getPrimaryIndexInAlteredTable(TableDiff $diff)
1144
    {
1145 254
        $primaryIndex = [];
1146
1147 254
        foreach ($this->getIndexesInAlteredTable($diff) as $index) {
1148 120
            if (! $index->isPrimary()) {
1149 97
                continue;
1150
            }
1151
1152 82
            $primaryIndex = [$index->getName() => $index];
1153
        }
1154
1155 254
        return $primaryIndex;
1156
    }
1157
}
1158