Failed Conditions
Push — master ( 94cec7...7f79d0 )
by Marco
25s queued 13s
created

SqlitePlatform::getForeignKeysInAlteredTable()   C

Complexity

Conditions 12
Paths 120

Size

Total Lines 51
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 12.0092

Importance

Changes 0
Metric Value
eloc 31
dl 0
loc 51
ccs 24
cts 25
cp 0.96
rs 6.8
c 0
b 0
f 0
cc 12
nc 120
nop 1
crap 12.0092

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

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

802
    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...
803
    {
804
        $table = str_replace('.', '__', $table);
805
806
        return sprintf('PRAGMA foreign_key_list(%s)', $this->quoteStringLiteral($table));
807 424
    }
808
809 424
    /**
810 424
     * {@inheritDoc}
811 33
     */
812
    public function getAlterTableSQL(TableDiff $diff)
813
    {
814 391
        $sql = $this->getSimpleAlterTableSQL($diff);
815 391
        if ($sql !== false) {
0 ignored issues
show
introduced by
The condition $sql !== false is always false.
Loading history...
816 54
            return $sql;
817
        }
818
819 337
        $fromTable = $diff->fromTable;
820
        if (! $fromTable instanceof Table) {
821 337
            throw new DBALException('Sqlite platform requires for alter table the table diff with reference to original table schema');
822 337
        }
823 337
824 337
        $table = clone $fromTable;
825
826 337
        $columns        = [];
827 310
        $oldColumnNames = [];
828 310
        $newColumnNames = [];
829 310
        $columnSql      = [];
830
831
        foreach ($table->getColumns() as $columnName => $column) {
832 337
            $columnName                  = strtolower($columnName);
833 109
            $columns[$columnName]        = $column;
834
            $oldColumnNames[$columnName] = $newColumnNames[$columnName] = $column->getQuotedName($this);
835
        }
836
837 109
        foreach ($diff->removedColumns as $columnName => $column) {
838 109
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
839
                continue;
840
            }
841
842
            $columnName = strtolower($columnName);
843 109
            if (! isset($columns[$columnName])) {
844 109
                continue;
845 109
            }
846
847
            unset(
848
                $columns[$columnName],
849 337
                $oldColumnNames[$columnName],
850 135
                $newColumnNames[$columnName]
851
            );
852
        }
853
854 135
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
855 135
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
856 135
                continue;
857
            }
858
859 135
            $oldColumnName = strtolower($oldColumnName);
860
            if (isset($columns[$oldColumnName])) {
861 135
                unset($columns[$oldColumnName]);
862
            }
863
864
            $columns[strtolower($column->getName())] = $column;
865 135
866
            if (! isset($newColumnNames[$oldColumnName])) {
867
                continue;
868 337
            }
869 174
870
            $newColumnNames[$oldColumnName] = $column->getQuotedName($this);
871
        }
872
873 174
        foreach ($diff->changedColumns as $oldColumnName => $columnDiff) {
874 147
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
875
                continue;
876
            }
877 174
878
            if (isset($columns[$oldColumnName])) {
879 174
                unset($columns[$oldColumnName]);
880 27
            }
881
882
            $columns[strtolower($columnDiff->column->getName())] = $columnDiff->column;
883 147
884
            if (! isset($newColumnNames[$oldColumnName])) {
885
                continue;
886 337
            }
887 82
888
            $newColumnNames[$oldColumnName] = $columnDiff->column->getQuotedName($this);
889
        }
890
891 82
        foreach ($diff->addedColumns as $columnName => $column) {
892
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
893
                continue;
894 337
            }
895 337
896 337
            $columns[strtolower($columnName)] = $column;
897 337
        }
898
899 337
        $sql      = [];
900 337
        $tableSql = [];
901
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
902 337
            $dataTable = new Table('__temp__' . $table->getName());
903
904 337
            $newTable = new Table($table->getQuotedName($this), $columns, $this->getPrimaryIndexInAlteredTable($diff), $this->getForeignKeysInAlteredTable($diff), 0, $table->getOptions());
905 337
            $newTable->addOption('alter', true);
906
907 337
            $sql = $this->getPreAlterTableIndexForeignKeySQL($diff);
908 337
            //$sql = array_merge($sql, $this->getCreateTableSQL($dataTable, 0));
909 337
            $sql[] = sprintf('CREATE TEMPORARY TABLE %s AS SELECT %s FROM %s', $dataTable->getQuotedName($this), implode(', ', $oldColumnNames), $table->getQuotedName($this));
910
            $sql[] = $this->getDropTableSQL($fromTable);
911 337
912 81
            $sql   = array_merge($sql, $this->getCreateTableSQL($newTable));
913 81
            $sql[] = sprintf('INSERT INTO %s (%s) SELECT %s FROM %s', $newTable->getQuotedName($this), implode(', ', $newColumnNames), implode(', ', $oldColumnNames), $dataTable->getQuotedName($this));
914
            $sql[] = $this->getDropTableSQL($dataTable);
915
916 337
            $newName = $diff->getNewName();
917
918
            if ($newName !== false) {
919 337
                $sql[] = sprintf(
920
                    'ALTER TABLE %s RENAME TO %s',
921
                    $newTable->getQuotedName($this),
922
                    $newName->getQuotedName($this)
923
                );
924
            }
925 424
926
            $sql = array_merge($sql, $this->getPostAlterTableIndexForeignKeySQL($diff));
927
        }
928 424
929 179
        return array_merge($sql, $tableSql, $columnSql);
930 71
    }
931 71
932 179
    /**
933
     * @return string[]|false
934 174
     */
935
    private function getSimpleAlterTableSQL(TableDiff $diff)
936
    {
937 5
        // Suppress changes on integer type autoincrement columns.
938 1
        foreach ($diff->changedColumns as $oldColumnName => $columnDiff) {
939
            if (! $columnDiff->fromColumn instanceof Column ||
940 1
                ! $columnDiff->column instanceof Column ||
941
                ! $columnDiff->column->getAutoincrement() ||
942
                ! $columnDiff->column->getType() instanceof Types\IntegerType
943 4
            ) {
944
                continue;
945 4
            }
946
947
            if (! $columnDiff->hasChanged('type') && $columnDiff->hasChanged('unsigned')) {
948
                unset($diff->changedColumns[$oldColumnName]);
949 4
950
                continue;
951
            }
952 424
953 289
            $fromColumnType = $columnDiff->fromColumn->getType();
954 169
955 424
            if (! ($fromColumnType instanceof Types\SmallIntType) && ! ($fromColumnType instanceof Types\BigIntType)) {
956
                continue;
957 337
            }
958
959
            unset($diff->changedColumns[$oldColumnName]);
960 87
        }
961
962 87
        if (! empty($diff->renamedColumns) || ! empty($diff->addedForeignKeys) || ! empty($diff->addedIndexes)
963 87
                || ! empty($diff->changedColumns) || ! empty($diff->changedForeignKeys) || ! empty($diff->changedIndexes)
964 87
                || ! empty($diff->removedColumns) || ! empty($diff->removedForeignKeys) || ! empty($diff->removedIndexes)
965
                || ! empty($diff->renamedIndexes)
966 87
        ) {
967 81
            return false;
968
        }
969
970
        $table = new Table($diff->name);
971 81
972 81
        $sql       = [];
973
        $tableSql  = [];
974 81
        $columnSql = [];
975 54
976 54
        foreach ($diff->addedColumns as $column) {
977 27
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
978 54
                continue;
979
            }
980
981 27
            $field = array_merge(['unique' => null, 'autoincrement' => null, 'default' => null], $column->toArray());
982 27
            $type  = $field['type'];
983 27
            switch (true) {
984
                case isset($field['columnDefinition']) || $field['autoincrement'] || $field['unique']:
985
                case $type instanceof Types\DateTimeType && $field['default'] === $this->getCurrentTimestampSQL():
986 27
                case $type instanceof Types\DateType && $field['default'] === $this->getCurrentDateSQL():
987
                case $type instanceof Types\TimeType && $field['default'] === $this->getCurrentTimeSQL():
988
                    return false;
989 33
            }
990 33
991 1
            $field['name'] = $column->getQuotedName($this);
992 1
            if ($type instanceof Types\StringType && $field['length'] === null) {
993
                $field['length'] = 255;
994
            }
995
996 33
            $sql[] = 'ALTER TABLE ' . $table->getQuotedName($this) . ' ADD COLUMN ' . $this->getColumnDeclarationSQL($field['name'], $field);
997
        }
998
999
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
1000
            if ($diff->newName !== false) {
1001
                $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

1001
                $newTable = new Identifier(/** @scrutinizer ignore-type */ $diff->newName);
Loading history...
1002 337
                $sql[]    = 'ALTER TABLE ' . $table->getQuotedName($this) . ' RENAME TO ' . $newTable->getQuotedName($this);
1003
            }
1004 337
        }
1005
1006 337
        return array_merge($sql, $tableSql, $columnSql);
1007 310
    }
1008
1009
    /**
1010 337
     * @return string[]
1011 109
     */
1012 109
    private function getColumnNamesInAlteredTable(TableDiff $diff)
1013
    {
1014
        $columns = [];
1015
1016 109
        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

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