Failed Conditions
Pull Request — master (#3260)
by Michael
61:30
created

getDateArithmeticIntervalExpression()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 7.2349

Importance

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

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

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

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